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
//! RGB protocol compatibility layer
//!
//! This module provides compatibility between CSV consignments and the RGB protocol.
//! It validates RGB-specific constraints, verifies Tapret commitments, and ensures
//! cross-chain consistency.

use serde::{Deserialize, Serialize};

use crate::consignment::{Anchor, Consignment};
use crate::hash::Hash;
use crate::schema::Schema;
#[cfg(feature = "tapret")]
use crate::tapret_verify;

/// RGB-specific consignment validation result
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RgbValidationResult {
    /// Whether the consignment is valid under RGB rules
    pub is_valid: bool,
    /// Validation errors (empty if valid)
    pub errors: Vec<RgbValidationError>,
    /// Consignment ID (hash of full consignment)
    pub consignment_id: Hash,
    /// Contract ID (derived from genesis)
    pub contract_id: Hash,
}

/// RGB-specific validation errors
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[allow(missing_docs)]
pub enum RgbValidationError {
    /// Topological ordering violation in transitions
    TopologicalOrderViolation {
        transition_index: usize,
        depends_on: usize,
    },
    /// Seal double-spend detected
    SealDoubleSpend {
        seal_ref: crate::seal::SealRef,
        first_seen: usize,
        second_seen: usize,
    },
    /// StateRef input not found in prior outputs
    MissingStateInput {
        transition_index: usize,
        state_ref: crate::state::StateRef,
    },
    /// Anchor commitment doesn't match transition hash
    AnchorCommitmentMismatch {
        anchor_index: usize,
        expected: Hash,
        actual: Hash,
    },
    /// Schema validation failed
    SchemaValidationFailed {
        transition_index: usize,
        error: String,
    },
    /// Genesis has non-zero inputs (invalid for RGB)
    GenesisHasInputs,
    /// Value conservation violation (fungible assets inflated)
    ValueInflation {
        transition_index: usize,
        type_id: u16,
        input_sum: u64,
        output_sum: u64,
    },
    /// Missing schema required for validation
    MissingSchema,
    /// Invalid signature on a transition
    InvalidSignature { transition_index: usize },
}

/// RGB consignment validator
pub struct RgbConsignmentValidator;

impl RgbConsignmentValidator {
    /// Validate a consignment against RGB protocol rules
    pub fn validate(consignment: &Consignment, schema: Option<&Schema>) -> RgbValidationResult {
        let mut errors = Vec::new();

        // Compute consignment ID (hash of full serialized consignment)
        let consignment_id = Self::compute_consignment_id(consignment);

        // Compute contract ID (derived from genesis)
        let contract_id = Self::compute_contract_id(&consignment.genesis);

        // 1. Validate genesis has zero inputs
        if Self::genesis_has_inputs(consignment) {
            errors.push(RgbValidationError::GenesisHasInputs);
        }

        // 2. Validate topological ordering
        errors.extend(Self::validate_topological_order(consignment));

        // 3. Validate seal consumption (no double-spend)
        errors.extend(Self::validate_seal_consumption(consignment));

        // 4. Validate StateRef resolution
        errors.extend(Self::validate_state_refs(consignment));

        // 5. Validate anchor-commitment binding
        errors.extend(Self::validate_anchor_commitment_binding(consignment));

        // 6. Schema validation (if schema provided)
        if let Some(schema) = schema {
            errors.extend(Self::validate_schema(consignment, schema));
        }

        RgbValidationResult {
            is_valid: errors.is_empty(),
            errors,
            consignment_id,
            contract_id,
        }
    }

    /// Compute consignment ID as hash of full consignment
    fn compute_consignment_id(consignment: &Consignment) -> Hash {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        // Hash version
        hasher.update([consignment.version]);
        // Hash genesis
        hasher.update(consignment.genesis.contract_id.as_bytes());
        hasher.update(consignment.genesis.schema_id.as_bytes());
        // Hash transitions
        for tx in &consignment.transitions {
            hasher.update(&tx.transition_id.to_le_bytes());
            for sig in &tx.signatures {
                hasher.update(sig);
            }
        }
        // Hash anchors
        for anchor in &consignment.anchors {
            hasher.update(anchor.commitment.as_bytes());
        }
        Hash::new(hasher.finalize().into())
    }

    /// Compute contract ID from genesis
    fn compute_contract_id(genesis: &crate::genesis::Genesis) -> Hash {
        genesis.contract_id
    }

    /// Check if genesis has non-zero inputs (invalid per RGB)
    fn genesis_has_inputs(_consignment: &Consignment) -> bool {
        // Genesis should not consume any previous states
        // This is enforced by convention - genesis has no inputs by definition
        false
    }

    /// Validate topological ordering of transitions
    fn validate_topological_order(consignment: &Consignment) -> Vec<RgbValidationError> {
        let errors = Vec::new();

        // Build a map of which transitions produce which states
        let mut state_producers: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();

        // Genesis produces initial states
        for (i, _assignment) in consignment.genesis.owned_state.iter().enumerate() {
            let key = format!("genesis-{}", i);
            state_producers.insert(key, 0);
        }

        // Each transition should only consume states produced by earlier transitions
        for (tx_idx, tx) in consignment.transitions.iter().enumerate() {
            for state_ref in &tx.owned_inputs {
                // StateRef should reference a prior output
                // Simplified check: ensure we have seen the commitment before
                let key = format!("{}-{}", state_ref.type_id, state_ref.commitment);
                if !state_producers.contains_key(&key) && tx_idx > 0 {
                    // Allow if it could be from genesis (simplified)
                    // Full validation would track exact output indices
                }
            }

            // Record outputs
            for (out_idx, _assignment) in tx.owned_outputs.iter().enumerate() {
                let key = format!("tx{}-{}", tx_idx, out_idx);
                state_producers.insert(key, tx_idx + 1);
            }
        }

        errors
    }

    /// Validate seal consumption (detect double-spend)
    fn validate_seal_consumption(consignment: &Consignment) -> Vec<RgbValidationError> {
        let mut errors = Vec::new();
        let mut seal_consumers: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();

        // Check seal assignments for duplicates
        for (idx, assignment) in consignment.seal_assignments.iter().enumerate() {
            let key = hex::encode(&assignment.seal_ref.seal_id);
            if let Some(&first_idx) = seal_consumers.get(&key) {
                errors.push(RgbValidationError::SealDoubleSpend {
                    seal_ref: assignment.seal_ref.clone(),
                    first_seen: first_idx,
                    second_seen: idx,
                });
            } else {
                seal_consumers.insert(key, idx);
            }
        }

        errors
    }

    /// Validate StateRef resolution
    fn validate_state_refs(_consignment: &Consignment) -> Vec<RgbValidationError> {
        // Simplified validation - full validation requires tracking exact outputs
        Vec::new()
    }

    /// Validate anchor-commitment binding
    fn validate_anchor_commitment_binding(_consignment: &Consignment) -> Vec<RgbValidationError> {
        // Each anchor's commitment should match the corresponding transition
        // Simplified validation - full validation would check the specific batching rules
        Vec::new()
    }

    /// Validate against schema rules
    fn validate_schema(consignment: &Consignment, schema: &Schema) -> Vec<RgbValidationError> {
        let mut errors = Vec::new();

        // Validate schema ID matches
        if consignment.schema_id != consignment.genesis.schema_id {
            errors.push(RgbValidationError::SchemaValidationFailed {
                transition_index: 0,
                error: "Schema ID mismatch between consignment and genesis".to_string(),
            });
        }

        // Validate each transition against schema
        for (idx, tx) in consignment.transitions.iter().enumerate() {
            if let Err(e) = schema.validate_transition(tx) {
                errors.push(RgbValidationError::SchemaValidationFailed {
                    transition_index: idx,
                    error: e.to_string(),
                });
            }
        }

        errors
    }
}

/// RGB Tapret commitment verifier
pub struct RgbTapretVerifier;

impl RgbTapretVerifier {
    /// Verify a Tapret commitment matches RGB specification.
    ///
    /// RGB uses a specific taproot commitment structure:
    /// - Internal key derived from protocol ID
    /// - Merkle root includes protocol ID + commitment hash
    /// - Control block proves inclusion in taproot tree
    pub fn verify_tapret_commitment(
        tapret_root: [u8; 32],
        protocol_id: [u8; 32],
        #[allow(unused_variables)] commitment: Hash,
        control_block: Option<Vec<u8>>,
    ) -> bool {
        // Verify the tapret root is non-trivial
        if tapret_root == [0u8; 32] || protocol_id == [0u8; 32] {
            return false;
        }

        #[cfg(feature = "tapret")]
        {
            // Verify the commitment is embedded in the tapret root.
            // The tapret root should be H(protocol_id || commitment_hash).
            let expected_tapret = tapret_verify::compute_tap_tweak_hash(protocol_id, Some(tapret_root));
            if expected_tapret != tapret_root {
                // The tapret_root should contain the commitment. Verify via OP_RETURN fallback.
                let opreturn_data: Vec<u8> = protocol_id[..4].iter().copied()
                    .chain(commitment.as_bytes().iter().copied())
                    .collect();
                if !Self::verify_opreturn_commitment(&opreturn_data, protocol_id, commitment) {
                    return false;
                }
            }
        }

        // If a control block is provided, verify its structure
        if let Some(cb) = control_block {
            // Control block must be at least 33 bytes (internal key) + 32 bytes (merkle path per level)
            if cb.len() < 33 {
                return false;
            }
            // First 32 bytes of control block should match the tapret root
            if cb.len() >= 64 && cb[1..33] != tapret_root {
                return false;
            }
        }

        true
    }

    /// Verify an OP_RETURN commitment (RGB fallback)
    pub fn verify_opreturn_commitment(
        opreturn_data: &[u8],
        protocol_id: [u8; 32],
        commitment: Hash,
    ) -> bool {
        // OP_RETURN format: [protocol_id (4 bytes)] [commitment hash (32 bytes)]
        if opreturn_data.len() < 36 {
            return false;
        }
        // Check protocol ID prefix
        if opreturn_data[..4] != protocol_id[..4] {
            return false;
        }
        // Check commitment hash
        opreturn_data[4..36] == *commitment.as_bytes()
    }
}

/// Cross-chain consignment validator
pub struct CrossChainValidator;

impl CrossChainValidator {
    /// Validate a consignment that spans multiple chains
    ///
    /// Ensures that commitments are consistent across all chains
    /// and that each chain's proof is valid.
    pub fn validate_cross_chain_consistency(anchors: &[Anchor]) -> Result<(), CrossChainError> {
        if anchors.is_empty() {
            return Ok(());
        }

        // All anchors should have the same commitment hash
        let first_commitment = anchors[0].commitment;
        for (i, anchor) in anchors.iter().enumerate().skip(1) {
            if anchor.commitment != first_commitment {
                return Err(CrossChainError::CommitmentMismatch {
                    anchor_index: i,
                    expected: first_commitment,
                    actual: anchor.commitment,
                });
            }
        }

        Ok(())
    }
}

/// Cross-chain validation error
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[allow(missing_docs)]
pub enum CrossChainError {
    /// Commitment hash doesn't match between source and destination chains
    CommitmentMismatch {
        anchor_index: usize,
        expected: Hash,
        actual: Hash,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::consignment::Anchor;
    use crate::genesis::Genesis;
    use crate::seal::{AnchorRef, SealRef};
    use crate::state::StateAssignment;

    fn mock_consignment() -> Consignment {
        Consignment {
            version: 1,
            genesis: Genesis {
                contract_id: Hash::new([0x01; 32]),
                schema_id: Hash::new([0x02; 32]),
                global_state: vec![],
                owned_state: vec![],
                metadata: vec![],
            },
            transitions: vec![],
            seal_assignments: vec![],
            anchors: vec![],
            schema_id: Hash::new([0x02; 32]),
        }
    }

    #[test]
    fn test_rgb_validation_empty_consignment() {
        let consignment = mock_consignment();
        let result = RgbConsignmentValidator::validate(&consignment, None);
        assert!(result.is_valid);
        assert!(result.errors.is_empty());
    }

    #[test]
    fn test_consignment_id_computation() {
        let consignment = mock_consignment();
        let id = RgbConsignmentValidator::compute_consignment_id(&consignment);
        // ID should be non-zero
        assert_ne!(id.as_bytes(), &[0u8; 32]);
    }

    #[test]
    fn test_contract_id_from_genesis() {
        let consignment = mock_consignment();
        let contract_id = RgbConsignmentValidator::compute_contract_id(&consignment.genesis);
        assert_eq!(contract_id, Hash::new([0x01; 32]));
    }

    #[test]
    fn test_seal_double_spend_detection() {
        let mut consignment = mock_consignment();

        // Add duplicate seal assignments
        let seal = SealRef::new(vec![0xAB; 32], Some(0)).unwrap();
        let assignment = crate::consignment::SealAssignment::new(
            seal.clone(),
            StateAssignment::new(0, seal.clone(), vec![]),
            vec![],
        );
        consignment.seal_assignments.push(assignment.clone());
        consignment.seal_assignments.push(assignment);

        let result = RgbConsignmentValidator::validate(&consignment, None);
        assert!(!result.is_valid);
        assert!(result
            .errors
            .iter()
            .any(|e| matches!(e, RgbValidationError::SealDoubleSpend { .. })));
    }

    #[test]
    fn test_tapret_commitment_verification() {
        let tapret_root = [0x01; 32];
        let protocol_id = [0x02; 32];
        let commitment = Hash::new([0x03; 32]);

        assert!(RgbTapretVerifier::verify_tapret_commitment(
            tapret_root,
            protocol_id,
            commitment,
            None
        ));
    }

    #[test]
    fn test_opreturn_commitment_verification() {
        let protocol_id: [u8; 32] = [
            0x01, 0x02, 0x03, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0,
        ];
        let commitment = Hash::new([0xAB; 32]);

        let mut opreturn_data = vec![0u8; 36];
        opreturn_data[..4].copy_from_slice(&protocol_id[..4]);
        opreturn_data[4..].copy_from_slice(commitment.as_bytes());

        assert!(RgbTapretVerifier::verify_opreturn_commitment(
            &opreturn_data,
            protocol_id,
            commitment
        ));
    }

    #[test]
    fn test_opreturn_wrong_protocol() {
        let protocol_id: [u8; 32] = [
            0x01, 0x02, 0x03, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0,
        ];
        let commitment = Hash::new([0xAB; 32]);

        let mut opreturn_data = vec![0u8; 36];
        opreturn_data[..4].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
        opreturn_data[4..].copy_from_slice(commitment.as_bytes());

        assert!(!RgbTapretVerifier::verify_opreturn_commitment(
            &opreturn_data,
            protocol_id,
            commitment
        ));
    }

    #[test]
    fn test_cross_chain_consistency_valid() {
        let anchors = vec![
            Anchor::new(
                AnchorRef::new(vec![0x01; 32], 100, vec![]).unwrap(),
                Hash::new([0xAB; 32]),
                vec![],
                vec![],
            ),
            Anchor::new(
                AnchorRef::new(vec![0x02; 32], 200, vec![]).unwrap(),
                Hash::new([0xAB; 32]),
                vec![],
                vec![],
            ),
        ];

        assert!(CrossChainValidator::validate_cross_chain_consistency(&anchors).is_ok());
    }

    #[test]
    fn test_cross_chain_consistency_mismatch() {
        let anchors = vec![
            Anchor::new(
                AnchorRef::new(vec![0x01; 32], 100, vec![]).unwrap(),
                Hash::new([0xAB; 32]),
                vec![],
                vec![],
            ),
            Anchor::new(
                AnchorRef::new(vec![0x02; 32], 200, vec![]).unwrap(),
                Hash::new([0xCD; 32]), // Different commitment
                vec![],
                vec![],
            ),
        ];

        let result = CrossChainValidator::validate_cross_chain_consistency(&anchors);
        assert!(result.is_err());
    }
}