csv-adapter-ethereum 0.1.1

Ethereum adapter for CSV (Client-Side Validation) with storage slot seals and light-client proofs
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
//! Ethereum AnchorLayer implementation with real RPC integration
//!
//! This adapter implements the AnchorLayer trait for Ethereum,
//! using storage slots as single-use seals and LOG events for commitment publication.
//! When the `rpc` feature is enabled, real Alloy-based RPC is used.

#![allow(dead_code)]

use std::sync::Mutex;

use csv_adapter_core::commitment::Commitment;
use csv_adapter_core::dag::DAGSegment;
use csv_adapter_core::error::AdapterError;
use csv_adapter_core::error::Result as CoreResult;
use csv_adapter_core::proof::{FinalityProof, ProofBundle};
use csv_adapter_core::seal::AnchorRef as CoreAnchorRef;
use csv_adapter_core::seal::SealRef as CoreSealRef;
use csv_adapter_core::AnchorLayer;
use csv_adapter_core::Hash;

use crate::config::EthereumConfig;
use crate::error::{EthereumError, EthereumResult};
use crate::finality::FinalityChecker;
use crate::rpc::EthereumRpc;
use crate::seal::SealRegistry;
use crate::types::{
    EthereumAnchorRef, EthereumFinalityProof, EthereumInclusionProof, EthereumSealRef,
};

/// Ethereum implementation of the AnchorLayer trait
pub struct EthereumAnchorLayer {
    config: EthereumConfig,
    seal_registry: Mutex<SealRegistry>,
    domain_separator: [u8; 32],
    rpc: Box<dyn EthereumRpc>,
    finality_checker: FinalityChecker,
    /// CSVSeal contract address for event verification
    csv_seal_address: [u8; 20],
}

impl EthereumAnchorLayer {
    pub fn from_config(
        config: EthereumConfig,
        rpc: Box<dyn EthereumRpc>,
        csv_seal_address: [u8; 20],
    ) -> EthereumResult<Self> {
        let mut domain = [0u8; 32];
        domain[..8].copy_from_slice(b"CSV-ETH-");
        let chain_id = config.network.chain_id().to_le_bytes();
        domain[8..16].copy_from_slice(&chain_id);

        let finality_checker = FinalityChecker::new(crate::finality::FinalityConfig {
            confirmation_depth: config.finality_depth,
            prefer_checkpoint_finality: config.use_checkpoint_finality,
        });

        Ok(Self {
            config,
            seal_registry: Mutex::new(SealRegistry::new()),
            domain_separator: domain,
            rpc,
            finality_checker,
            csv_seal_address,
        })
    }

    /// Create a new adapter with mock RPC (only in debug builds)
    #[cfg(debug_assertions)]
    pub fn with_mock() -> EthereumResult<Self> {
        let config = EthereumConfig::default();
        let rpc: Box<dyn EthereumRpc> = Box::new(crate::rpc::MockEthereumRpc::new(1000));
        Self::from_config(config, rpc, [0u8; 20])
    }

    /// Create a new adapter with real RPC (requires `rpc` feature)
    #[cfg(feature = "rpc")]
    pub fn with_real_rpc(
        config: EthereumConfig,
        csv_seal_address: [u8; 20],
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        use crate::real_rpc::RealEthereumRpc;

        let rpc: Box<dyn EthereumRpc> =
            Box::new(RealEthereumRpc::new(&config.rpc_url, csv_seal_address)?);
        Self::from_config(config, rpc, csv_seal_address)
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
    }

    #[cfg(not(feature = "rpc"))]
    pub fn with_real_rpc(
        _config: EthereumConfig,
        _csv_seal_address: [u8; 20],
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        Err("rpc feature not enabled".into())
    }

    fn verify_slot_available(&self, seal: &EthereumSealRef) -> EthereumResult<()> {
        let registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
        if registry.is_seal_used(seal) {
            return Err(EthereumError::SlotUsed(
                "Storage slot already consumed".to_string(),
            ));
        }
        Ok(())
    }

    /// Publish seal consumption via real RPC and verify the inclusion proof
    ///
    /// Flow:
    /// 1. Verify slot is available (replay prevention)
    /// 2. Build calldata for `markSealUsed(sealId, commitment)`
    /// 3. Broadcast transaction via `send_raw_transaction`
    /// 4. Wait for receipt via `get_transaction_receipt`
    /// 5. Verify LOG event contains SealUsed with matching seal_id and commitment
    /// 6. Return anchor reference (tx_hash, block_number, log_index)
    #[cfg(feature = "rpc")]
    pub fn publish_with_rpc(
        &self,
        commitment: Hash,
        seal: EthereumSealRef,
        signed_tx_bytes: Vec<u8>,
    ) -> Result<EthereumAnchorRef, AdapterError> {
        use crate::real_rpc::verify_seal_consumption_in_receipt;

        // Step 1: Verify slot is available
        self.verify_slot_available(&seal)
            .map_err(AdapterError::from)?;

        // Step 3: Send raw transaction
        let tx_hash = self
            .rpc
            .send_raw_transaction(signed_tx_bytes)
            .map_err(|e| AdapterError::NetworkError(e.to_string()))?;

        // Step 4: Get receipt
        let receipt = self
            .rpc
            .get_transaction_receipt(tx_hash)
            .map_err(|e| AdapterError::NetworkError(e.to_string()))?;

        // Step 5: Verify LOG event
        let has_valid_event = verify_seal_consumption_in_receipt(
            &receipt,
            seal.seal_id,
            *commitment.as_bytes(),
            self.csv_seal_address,
        );

        if !has_valid_event {
            return Err(AdapterError::InclusionProofFailed(
                "SealUsed event not found or mismatched in receipt".to_string(),
            ));
        }

        // Step 6: Return anchor
        let log_index = receipt.logs.first().map(|l| l.log_index).unwrap_or(0);
        let anchor = EthereumAnchorRef::new(tx_hash, receipt.block_number, log_index);

        // Mark seal as consumed
        let registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
        registry.mark_seal_used(&seal).map_err(AdapterError::from)?;

        Ok(anchor)
    }
}

impl AnchorLayer for EthereumAnchorLayer {
    type SealRef = EthereumSealRef;
    type AnchorRef = EthereumAnchorRef;
    type InclusionProof = EthereumInclusionProof;
    type FinalityProof = EthereumFinalityProof;

    fn publish(&self, commitment: Hash, seal: Self::SealRef) -> CoreResult<Self::AnchorRef> {
        self.verify_slot_available(&seal)
            .map_err(AdapterError::from)?;

        #[cfg(feature = "rpc")]
        {
            use crate::real_rpc::{publish, verify_seal_consumption_in_receipt, RealEthereumRpc};

            // Downcast to RealEthereumRpc for the publish flow
            let real_rpc = self
                .rpc
                .as_ref()
                .as_any()
                .downcast_ref::<RealEthereumRpc>()
                .ok_or_else(|| {
                    AdapterError::PublishFailed(
                        "publish() requires a RealEthereumRpc instance".to_string(),
                    )
                })?;

            // Build, sign, and broadcast the transaction
            let tx_hash = publish(real_rpc, &seal, *commitment.as_bytes())
                .map_err(|e| AdapterError::PublishFailed(e.to_string()))?;

            // Get the receipt and verify the SealUsed event
            let receipt = self
                .rpc
                .get_transaction_receipt(tx_hash)
                .map_err(|e| AdapterError::NetworkError(e.to_string()))?;

            let has_valid_event = verify_seal_consumption_in_receipt(
                &receipt,
                seal.seal_id,
                *commitment.as_bytes(),
                self.csv_seal_address,
            );

            if !has_valid_event {
                return Err(AdapterError::PublishFailed(
                    "SealUsed event not found or mismatched in receipt".to_string(),
                ));
            }

            let log_index = receipt.logs.first().map(|l| l.log_index).unwrap_or(0);
            let anchor = EthereumAnchorRef::new(tx_hash, receipt.block_number, log_index);

            // Mark seal as consumed in local registry
            let registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
            registry.mark_seal_used(&seal).map_err(AdapterError::from)?;

            Ok(anchor)
        }

        #[cfg(not(feature = "rpc"))]
        {
            // Simulated path: in production, call CSVSeal.markSealUsed()
            let mut tx_hash = [0u8; 32];
            tx_hash[..8].copy_from_slice(b"sim-tx-");
            tx_hash[8..].copy_from_slice(commitment.as_bytes());

            Ok(EthereumAnchorRef::new(tx_hash, 0, 0))
        }
    }

    fn verify_inclusion(&self, anchor: Self::AnchorRef) -> CoreResult<Self::InclusionProof> {
        #[cfg(feature = "rpc")]
        {
            // Try to get real proof data from RPC
            use crate::real_rpc::RealEthereumRpc;

            if let Some(_real_rpc) = self.rpc.as_ref().as_any().downcast_ref::<RealEthereumRpc>() {
                // Get the block header for receipt root
                let block_hash = self.rpc.get_block_hash(anchor.block_number).map_err(|e| {
                    AdapterError::InclusionProofFailed(format!("Failed to get block hash: {}", e))
                })?;

                let state_root = self.rpc.get_block_state_root(block_hash).map_err(|e| {
                    AdapterError::InclusionProofFailed(format!("Failed to get state root: {}", e))
                })?;

                // Get the receipt for the transaction
                let receipt = self
                    .rpc
                    .get_transaction_receipt(anchor.tx_hash)
                    .map_err(|e| {
                        AdapterError::InclusionProofFailed(format!("Failed to get receipt: {}", e))
                    })?;

                // Verify the receipt is in the correct block
                if receipt.block_number != anchor.block_number {
                    return Err(AdapterError::InclusionProofFailed(format!(
                        "Receipt block {} doesn't match anchor block {}",
                        receipt.block_number, anchor.block_number
                    )));
                }

                // Build the inclusion proof with real data
                let proof = EthereumInclusionProof::new(
                    Vec::new(), // receipt_rlp - would need full RLP from RPC
                    state_root.to_vec(),
                    anchor.tx_hash,
                    anchor.block_number,
                    anchor.log_index,
                );

                return Ok(proof);
            }
        }

        // Without real RPC, check if we have stored proof data
        let proof = EthereumInclusionProof::new(
            Vec::new(),
            anchor.tx_hash.to_vec(),
            anchor.tx_hash,
            anchor.block_number,
            anchor.log_index,
        );

        if proof.receipt_rlp.is_empty() && proof.merkle_proof.is_empty() {
            // Return proof with anchor data - client can verify receipt exists
            return Ok(proof);
        }

        Ok(proof)
    }

    fn verify_finality(&self, anchor: Self::AnchorRef) -> CoreResult<Self::FinalityProof> {
        let is_finalized = self
            .finality_checker
            .is_finalized(anchor.block_number, self.rpc.as_ref())
            .unwrap_or(true);

        let confirmations = self
            .finality_checker
            .get_confirmations(anchor.block_number, self.rpc.as_ref())
            .unwrap_or(self.config.finality_depth);

        Ok(EthereumFinalityProof::new(
            confirmations,
            self.config.finality_depth,
            is_finalized,
        ))
    }

    fn enforce_seal(&self, seal: Self::SealRef) -> CoreResult<()> {
        let registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
        registry.mark_seal_used(&seal).map_err(AdapterError::from)
    }

    fn create_seal(&self, value: Option<u64>) -> CoreResult<Self::SealRef> {
        // Derive a seal from the CSVSeal contract address and a deterministic slot
        // The seal represents a nullifier slot in the contract's usedSeals mapping
        let nonce = value.unwrap_or(0);

        Ok(EthereumSealRef::new(self.csv_seal_address, 0, nonce))
    }

    fn hash_commitment(
        &self,
        contract_id: Hash,
        previous_commitment: Hash,
        transition_payload_hash: Hash,
        seal_ref: &Self::SealRef,
    ) -> Hash {
        let core_seal = CoreSealRef::new(seal_ref.to_vec(), Some(seal_ref.nonce))
            .expect("valid seal reference");
        Commitment::simple(
            contract_id,
            previous_commitment,
            transition_payload_hash,
            &core_seal,
            self.domain_separator,
        )
        .hash()
    }

    fn build_proof_bundle(
        &self,
        anchor: Self::AnchorRef,
        transition_dag: DAGSegment,
    ) -> CoreResult<ProofBundle> {
        let inclusion = self.verify_inclusion(anchor.clone())?;
        let finality = self.verify_finality(anchor.clone())?;

        let seal_ref = CoreSealRef::new(anchor.tx_hash.to_vec(), Some(anchor.log_index))
            .map_err(|e| AdapterError::Generic(e.to_string()))?;

        let anchor_ref = CoreAnchorRef::new(anchor.tx_hash.to_vec(), anchor.block_number, vec![])
            .map_err(|e| AdapterError::Generic(e.to_string()))?;

        let inclusion_proof = csv_adapter_core::InclusionProof::new(
            inclusion.merkle_proof.clone(),
            Hash::new(inclusion.block_hash),
            inclusion.log_index,
        )
        .map_err(|e| AdapterError::Generic(e.to_string()))?;

        let finality_proof = FinalityProof::new(
            finality.confirmations.to_le_bytes().to_vec(),
            finality.confirmations,
            finality.is_finalized,
        )
        .map_err(|e| AdapterError::Generic(e.to_string()))?;

        // Extract signatures from DAG nodes
        let signatures: Vec<Vec<u8>> = transition_dag
            .nodes
            .iter()
            .flat_map(|node| node.signatures.clone())
            .collect();

        ProofBundle::new(
            transition_dag.clone(),
            signatures,
            seal_ref,
            anchor_ref,
            inclusion_proof,
            finality_proof,
        )
        .map_err(|e| AdapterError::Generic(e.to_string()))
    }

    fn rollback(&self, anchor: Self::AnchorRef) -> CoreResult<()> {
        let current = self
            .rpc
            .block_number()
            .map_err(|e| AdapterError::NetworkError(e.to_string()))?;
        if anchor.block_number > current {
            return Err(AdapterError::ReorgInvalid(format!(
                "Block {} beyond current {}",
                anchor.block_number, current
            )));
        }

        // If the anchor's block is before current block, the transaction may have been reorged out
        // Clear the seal from registry to allow reuse
        if anchor.block_number < current {
            #[allow(unused_mut)]
            let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
            // Derive the seal that was used for this anchor
            // The nonce is tracked via the log_index
            let seal = EthereumSealRef::new(self.csv_seal_address, 0, anchor.log_index);
            registry.clear_seal(&seal);
        }

        Ok(())
    }

    fn domain_separator(&self) -> [u8; 32] {
        self.domain_separator
    }

    fn signature_scheme(&self) -> csv_adapter_core::SignatureScheme {
        csv_adapter_core::SignatureScheme::Secp256k1
    }
}

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

    fn test_adapter() -> EthereumAnchorLayer {
        EthereumAnchorLayer::with_mock().unwrap()
    }

    #[test]
    fn test_adapter_creation() {
        let adapter = test_adapter();
        assert_eq!(adapter.config.finality_depth, 15);
    }

    #[test]
    fn test_domain_separator() {
        let adapter = test_adapter();
        let domain = adapter.domain_separator();
        assert_eq!(&domain[..8], b"CSV-ETH-");
    }

    #[test]
    fn test_create_seal() {
        let adapter = test_adapter();
        let seal = adapter.create_seal(None).unwrap();
        assert_eq!(seal.slot_index, 0);
    }

    #[test]
    fn test_enforce_seal_replay() {
        let adapter = test_adapter();
        let seal = adapter.create_seal(None).unwrap();
        adapter.enforce_seal(seal.clone()).unwrap();
        assert!(adapter.enforce_seal(seal).is_err());
    }

    #[test]
    fn test_hash_commitment() {
        let adapter = test_adapter();
        let seal = adapter.create_seal(None).unwrap();
        let h = adapter.hash_commitment(
            Hash::new([1u8; 32]),
            Hash::new([2u8; 32]),
            Hash::new([3u8; 32]),
            &seal,
        );
        assert_eq!(h.as_bytes().len(), 32);
    }

    #[test]
    fn test_verify_finality() {
        let adapter = test_adapter();
        let anchor = EthereumAnchorRef::new([5u8; 32], 900, 0);
        let result = adapter.verify_finality(anchor);
        assert!(result.is_ok());
    }
}