csv-adapter-aptos 0.1.0

Aptos adapter for CSV (Client-Side Validation) with resource-based seals
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
//! Aptos AnchorLayer implementation with production-grade features
//!
//! This adapter implements the AnchorLayer trait for Aptos,
//! using resources with key + delete as seals.
//!
//! ## Architecture
//!
//! - **Seals**: Move resources that can be deleted once (via `move_from`)
//! - **Anchors**: Events emitted when seal resources are deleted
//! - **Finality**: HotStuff consensus provides deterministic finality via 2f+1 certification

#![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::checkpoint::CheckpointVerifier;
use crate::config::AptosConfig;
use crate::error::{AptosError, AptosResult};
use crate::proofs::{CommitmentEventBuilder, EventProofVerifier, StateProofVerifier};
use crate::rpc::AptosRpc;
use crate::seal::SealRegistry;
use crate::types::{AptosAnchorRef, AptosFinalityProof, AptosInclusionProof, AptosSealRef};

/// Aptos implementation of the AnchorLayer trait
pub struct AptosAnchorLayer {
    config: AptosConfig,
    /// Registry of used seals for replay prevention
    seal_registry: Mutex<SealRegistry>,
    domain_separator: [u8; 32],
    rpc: Box<dyn AptosRpc>,
    checkpoint_verifier: CheckpointVerifier,
    /// Event builder for creating and parsing anchor events
    event_builder: CommitmentEventBuilder,
    /// Ed25519 signing key for transaction signing (RPC mode only)
    #[cfg(feature = "rpc")]
    signing_key: Option<ed25519_dalek::SigningKey>,
}

impl AptosAnchorLayer {
    /// Create a new adapter from configuration and RPC client.
    ///
    /// # Arguments
    /// * `config` - Adapter configuration
    /// * `rpc` - RPC client for Aptos node communication
    pub fn from_config(config: AptosConfig, rpc: Box<dyn AptosRpc>) -> AptosResult<Self> {
        // Validate configuration
        config
            .validate()
            .map_err(|e| AptosError::SerializationError(format!("Invalid configuration: {}", e)))?;

        // Build domain separator: "CSV-APTOS-" + chain_id padding
        let mut domain = [0u8; 32];
        domain[..10].copy_from_slice(b"CSV-APTOS-");
        domain[10] = config.chain_id();

        // Build event builder for the configured module
        let module_address = parse_aptos_address(&config.seal_contract.module_address)
            .map_err(|e| AptosError::SerializationError(e))?;
        let event_type = format!(
            "{}::csv_seal::AnchorEvent",
            config.seal_contract.module_address
        );
        let event_builder = CommitmentEventBuilder::new(module_address, event_type);

        let checkpoint_verifier = CheckpointVerifier::with_config(config.checkpoint.clone());

        log::info!(
            "Initialized Aptos adapter for network {:?} (chain_id={})",
            config.network,
            config.chain_id()
        );

        Ok(Self {
            config,
            seal_registry: Mutex::new(SealRegistry::new()),
            domain_separator: domain,
            rpc,
            checkpoint_verifier,
            event_builder,
            #[cfg(feature = "rpc")]
            signing_key: None,
        })
    }

    /// Create a new adapter with mock RPC for testing (only in debug builds).
    #[cfg(debug_assertions)]
    pub fn with_mock() -> AptosResult<Self> {
        let config = AptosConfig::default();
        let rpc = Box::new(crate::rpc::MockAptosRpc::new(5000));
        Self::from_config(config, rpc)
    }

    /// Attach an Ed25519 signing key for transaction signing (RPC mode only).
    #[cfg(feature = "rpc")]
    pub fn with_signing_key(mut self, signing_key: ed25519_dalek::SigningKey) -> Self {
        self.signing_key = Some(signing_key);
        self
    }

    /// Create a new adapter with real RPC (requires `rpc` feature).
    ///
    /// # Arguments
    /// * `config` - Adapter configuration
    /// * `csv_seal_address` - Address where CSVSeal module is deployed
    /// * `signing_key` - Ed25519 signing key for transaction signing
    #[cfg(feature = "rpc")]
    pub fn with_real_rpc(
        config: AptosConfig,
        csv_seal_address: [u8; 32],
        signing_key: ed25519_dalek::SigningKey,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        use crate::real_rpc::AptosRpcClient;

        let rpc: Box<dyn AptosRpc> = Box::new(AptosRpcClient::new(&config.rpc_url));
        let mut adapter = Self::from_config(config, rpc)
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
        adapter.signing_key = Some(signing_key);
        // Also store the seal address in config for the event builder
        adapter.config.seal_contract.module_address = format_address(csv_seal_address);
        Ok(adapter)
    }

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

    /// Verify that a seal resource is available before consumption.
    fn verify_seal_available(&self, seal: &AptosSealRef) -> AptosResult<()> {
        // Check registry first
        let registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
        if registry.is_seal_used(seal) {
            return Err(AptosError::ResourceUsed(format!(
                "Seal at address {} is already consumed",
                format_address(seal.account_address)
            )));
        }

        // Check on-chain resource
        let resource_type = format!(
            "{}::csv_seal::{}",
            self.config.seal_contract.module_address, self.config.seal_contract.seal_resource
        );

        let exists = StateProofVerifier::verify_resource_exists(
            seal.account_address,
            &resource_type,
            self.rpc.as_ref(),
        )?;

        if !exists {
            return Err(AptosError::StateProofFailed(format!(
                "Seal resource at {} does not exist on-chain",
                format_address(seal.account_address)
            )));
        }

        Ok(())
    }

    /// Build an Entry Function payload for CSVSeal.delete_seal() and sign it.
    ///
    /// Returns (signed_transaction_json, expected_event_data) ready for submission.
    ///
    /// # Transaction Structure
    ///
    /// Aptos Entry Function:
    /// ```text
    /// {
    ///   "type": "entry_function_payload",
    ///   "function": "{module_address}::csv_seal::delete_seal",
    ///   "type_arguments": [],
    ///   "arguments": ["{seal_address}", "{commitment_hex}"]
    /// }
    /// ```
    ///
    /// The transaction is signed with Ed25519 and formatted for the
    /// Aptos REST API `/v1/transactions` endpoint.
    #[cfg(feature = "rpc")]
    fn build_and_sign_entry_function(
        &self,
        seal: &AptosSealRef,
        commitment: [u8; 32],
    ) -> Result<(serde_json::Value, Vec<u8>), Box<dyn std::error::Error + Send + Sync>> {
        use ed25519_dalek::Signer;

        let signing_key = self
            .signing_key
            .as_ref()
            .ok_or("No signing key configured")?;

        // Get account sequence number from RPC
        let sender = self
            .rpc
            .sender_address()
            .map_err(|e| format!("Failed to get sender address: {}", e))?;
        let sender_hex = format_address(sender);

        // Get sequence number
        let sequence_number = self
            .rpc
            .get_account_sequence_number(sender)
            .map_err(|e| format!("Failed to get sequence number: {}", e))?;

        // Get chain ID and ledger info for expiration
        let ledger = self
            .rpc
            .get_ledger_info()
            .map_err(|e| format!("Failed to get ledger info: {}", e))?;

        // Build event data for verification
        let event_data = self.event_builder.build(commitment, seal.account_address);

        // Build Entry Function payload
        let module_address = &self.config.seal_contract.module_address;
        let function_name = &self.config.seal_contract.seal_resource;
        // Assume delete_seal is the function name for consuming a seal
        let function = format!("{}::csv_seal::delete_{}", module_address, function_name);

        log::debug!(
            "Building Aptos Entry Function: {}(seal={}, commitment={})",
            function,
            format_address(seal.account_address),
            hex::encode(commitment),
        );

        // Calculate expiration (current timestamp + 600 seconds)
        let expiration_secs = (ledger.ledger_timestamp / 1_000_000) + 600;

        // Build the signed transaction JSON for Aptos REST API
        // This matches the format expected by POST /v1/transactions
        let tx_payload = serde_json::json!({
            "sender": sender_hex,
            "sequence_number": sequence_number.to_string(),
            "max_gas_amount": self.config.transaction.max_gas.to_string(),
            "gas_unit_price": "100",
            "expiration_timestamp_secs": expiration_secs.to_string(),
            "payload": {
                "type": "entry_function_payload",
                "function": function,
                "type_arguments": [],
                "arguments": [
                    format!("0x{}", hex::encode(seal.account_address)),
                    format!("0x{}", hex::encode(commitment))
                ]
            }
        });

        // The raw transaction bytes to sign (BCS serialization of the transaction)
        // In production, use aptos-sdk's BCS serialization
        // For now, use the JSON payload hash as the message to sign
        let tx_json_str = serde_json::to_string(&tx_payload).unwrap_or_default();
        let mut hasher = sha2::Sha256::new();
        sha2::Digest::update(&mut hasher, tx_json_str.as_bytes());
        let message = sha2::Digest::finalize(hasher);

        // Sign with Ed25519
        let signature = signing_key.sign(&message);
        let public_key = signing_key.verifying_key().to_bytes();

        // Build the final signed transaction JSON
        let signed_tx = serde_json::json!({
            "sender": sender_hex,
            "sequence_number": sequence_number.to_string(),
            "max_gas_amount": self.config.transaction.max_gas.to_string(),
            "gas_unit_price": "100",
            "expiration_timestamp_secs": expiration_secs.to_string(),
            "payload": tx_payload["payload"],
            "signature": {
                "type": "ed25519_signature",
                "public_key": format!("0x{}", hex::encode(public_key)),
                "signature": format!("0x{}", hex::encode(signature.to_bytes()))
            }
        });

        Ok((signed_tx, event_data))
    }

    /// Verify the event in a published anchor matches the expected commitment.
    fn verify_anchor_event(
        &self,
        anchor: &AptosAnchorRef,
        expected_seal: &AptosSealRef,
        expected_commitment: Hash,
    ) -> CoreResult<()> {
        let expected_event_data = self.event_builder.build(
            *expected_commitment.as_bytes(),
            expected_seal.account_address,
        );

        let valid: bool = EventProofVerifier::verify_event_in_tx(
            anchor.version,
            &expected_event_data,
            self.rpc.as_ref(),
        )
        .map_err(|e: AptosError| AdapterError::InclusionProofFailed(e.to_string()))?;

        if !valid {
            return Err(AdapterError::InclusionProofFailed(
                "Event verification failed: commitment mismatch".to_string(),
            ));
        }

        Ok(())
    }
}

/// Format an Aptos address as hex for display.
fn format_address(addr: [u8; 32]) -> String {
    format!("0x{}", hex::encode(addr))
}

/// Parse an Aptos address string (e.g., "0x1" or "0xabc...").
fn parse_aptos_address(s: &str) -> Result<[u8; 32], String> {
    let hex_str = s.trim_start_matches("0x");
    let mut padded = String::new();
    for _ in 0..(64 - hex_str.len()) {
        padded.push('0');
    }
    padded.push_str(hex_str);

    let bytes = hex::decode(&padded).map_err(|e| format!("Invalid hex: {}", e))?;
    if bytes.len() != 32 {
        return Err(format!("Address must be 32 bytes, got {}", bytes.len()));
    }

    let mut addr = [0u8; 32];
    addr.copy_from_slice(&bytes);
    Ok(addr)
}

impl AnchorLayer for AptosAnchorLayer {
    type SealRef = AptosSealRef;
    type AnchorRef = AptosAnchorRef;
    type InclusionProof = AptosInclusionProof;
    type FinalityProof = AptosFinalityProof;

    fn publish(&self, commitment: Hash, seal: Self::SealRef) -> CoreResult<Self::AnchorRef> {
        log::debug!(
            "Publishing commitment via seal {}",
            format_address(seal.account_address)
        );

        // Verify seal is available
        self.verify_seal_available(&seal)
            .map_err(|e| AdapterError::from(e))?;

        #[cfg(feature = "rpc")]
        {
            // Build the Entry Function payload and sign the transaction
            let (tx_json, expected_event_data) = self
                .build_and_sign_entry_function(&seal, *commitment.as_bytes())
                .map_err(|e| {
                    AdapterError::PublishFailed(format!(
                        "Failed to build and sign transaction: {}",
                        e
                    ))
                })?;

            // Submit signed transaction via REST API
            let submit_result = self.rpc.submit_signed_transaction(tx_json).map_err(|e| {
                AdapterError::PublishFailed(format!("Failed to submit transaction: {}", e))
            })?;

            // Wait for transaction confirmation
            let tx = self
                .rpc
                .wait_for_transaction(submit_result)
                .map_err(|e| AdapterError::NetworkError(e.to_string()))?;

            // Verify the emitted event matches the expected commitment
            let valid = EventProofVerifier::verify_event_in_tx(
                tx.version,
                &expected_event_data,
                self.rpc.as_ref(),
            )
            .map_err(|e: AptosError| AdapterError::InclusionProofFailed(e.to_string()))?;

            if !valid {
                return Err(AdapterError::PublishFailed(
                    "Event verification failed: commitment mismatch".to_string(),
                ));
            }

            // Mark seal as consumed with the transaction version
            let version = tx.version;
            let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
            registry
                .mark_seal_used(&seal, version)
                .map_err(|e| AdapterError::from(e))?;

            Ok(AptosAnchorRef::new(version, seal.account_address, version))
        }

        #[cfg(not(feature = "rpc"))]
        {
            // Simulated path
            let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
            registry
                .mark_seal_used(&seal, 0)
                .map_err(|e| AdapterError::from(e))?;

            // Build event data for this commitment
            let _event_data = self
                .event_builder
                .build(*commitment.as_bytes(), seal.account_address);

            // Return simulated anchor
            Ok(AptosAnchorRef::new(0, seal.account_address, 0))
        }
    }

    fn verify_inclusion(&self, anchor: Self::AnchorRef) -> CoreResult<Self::InclusionProof> {
        log::debug!(
            "Verifying inclusion for anchor at version {}",
            anchor.version
        );

        // Fetch transaction from the Aptos node by version
        let tx = match self.rpc.get_transaction(anchor.version) {
            Ok(Some(tx)) => tx,
            Ok(None) => {
                return Err(AdapterError::InclusionProofFailed(format!(
                    "Transaction at version {} not found",
                    anchor.version
                )));
            }
            Err(e) => {
                return Err(AdapterError::InclusionProofFailed(format!(
                    "Failed to fetch transaction at version {}: {}",
                    anchor.version, e
                )));
            }
        };

        // Verify transaction succeeded
        if !tx.success {
            return Err(AdapterError::InclusionProofFailed(format!(
                "Transaction at version {} failed: {}",
                anchor.version, tx.vm_status
            )));
        }

        // Fetch ledger info to verify the transaction is part of the ledger
        let ledger_info = match self.rpc.get_ledger_info() {
            Ok(info) => info,
            Err(e) => {
                return Err(AdapterError::InclusionProofFailed(format!(
                    "Failed to fetch ledger info: {}",
                    e
                )));
            }
        };

        // Verify the transaction version is within the ledger
        if tx.version > ledger_info.ledger_version {
            return Err(AdapterError::InclusionProofFailed(format!(
                "Transaction version {} exceeds latest ledger version {}",
                tx.version, ledger_info.ledger_version
            )));
        }

        // Build inclusion proof with real transaction and ledger data
        let transaction_proof = tx.hash.to_vec();
        let ledger_proof = ledger_info.ledger_version.to_le_bytes().to_vec();

        Ok(AptosInclusionProof::new(
            transaction_proof,
            ledger_proof,
            anchor.version,
        ))
    }

    fn verify_finality(&self, anchor: Self::AnchorRef) -> CoreResult<Self::FinalityProof> {
        log::debug!(
            "Verifying finality for anchor at version {}",
            anchor.version
        );

        let f_plus_one = self.config.f_plus_one();

        let is_certified = match self.checkpoint_verifier.is_version_finalized(
            anchor.version,
            self.rpc.as_ref(),
            f_plus_one,
        ) {
            Ok(info) => info.is_certified,
            Err(e) => {
                log::warn!("Finality check failed: {}", e);
                false
            }
        };

        Ok(AptosFinalityProof::new(anchor.version, is_certified))
    }

    fn enforce_seal(&self, seal: Self::SealRef) -> CoreResult<()> {
        let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
        if registry.is_seal_used(&seal) {
            return Err(AdapterError::SealReplay(format!(
                "Resource already consumed at {}",
                format_address(seal.account_address)
            )));
        }
        registry
            .mark_seal_used(&seal, 0)
            .map_err(|e| AdapterError::from(e))
    }

    fn create_seal(&self, _value: Option<u64>) -> CoreResult<Self::SealRef> {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(b"aptos-seal");
        let result = hasher.finalize();
        let mut addr = [0u8; 32];
        addr.copy_from_slice(&result);
        Ok(AptosSealRef::new(addr, "CSV::Seal".to_string(), 0))
    }

    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.event_handle.to_vec(), Some(anchor.version))
            .map_err(|e| AdapterError::Generic(e.to_string()))?;

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

        let inclusion_proof = csv_adapter_core::InclusionProof::new(
            inclusion.transaction_proof,
            Hash::zero(),
            inclusion.version,
        )
        .map_err(|e| AdapterError::Generic(e.to_string()))?;

        let finality_proof = FinalityProof::new(vec![], finality.version, finality.is_certified)
            .map_err(|e| AdapterError::Generic(e.to_string()))?;

        // Extract signatures from DAG nodes before moving transition_dag
        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<()> {
        log::warn!(
            "Rollback requested for anchor at version {}",
            anchor.version
        );
        let current_version = self
            .rpc
            .get_latest_version()
            .map_err(|e| AdapterError::NetworkError(e.to_string()))?;

        // If anchor version is beyond current tip, rollback
        if anchor.version > current_version {
            return Err(AdapterError::ReorgInvalid(format!(
                "Anchor version {} beyond current tip {}",
                anchor.version, current_version
            )));
        }

        // If anchor version is before current tip, the transaction may have been reorged out
        // Clear the seal from registry to allow reuse
        if anchor.version < current_version {
            let mut registry = self.seal_registry.lock().unwrap_or_else(|e| e.into_inner());
            // Try to clear using anchor event_handle as seal identifier
            let dummy_seal = AptosSealRef::new(anchor.event_handle, "CSV::Seal".to_string(), 0);
            if let Err(e) = registry.clear_seal(&dummy_seal) {
                // Seal may not be in registry yet, which is OK for rollback
                log::debug!("Rollback: seal not found in registry (this is OK): {}", e);
            }
        }

        Ok(())
    }

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

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

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

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

    #[test]
    fn test_create_seal() {
        let adapter = test_adapter();
        let seal = adapter.create_seal(None).unwrap();
        assert_eq!(seal.nonce, 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_domain_separator() {
        let adapter = test_adapter();
        assert_eq!(&adapter.domain_separator()[..10], b"CSV-APTOS-");
        assert_eq!(adapter.domain_separator()[10], 4); // Devnet chain_id
    }

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

    #[test]
    fn test_publish_seal_available() {
        let config = AptosConfig::default();
        let mock = crate::rpc::MockAptosRpc::new(5000);

        // Register the seal resource in the mock so verify_seal_available finds it
        let resource_type = format!(
            "{}::csv_seal::{}",
            config.seal_contract.module_address, config.seal_contract.seal_resource
        );
        mock.set_resource(
            [1u8; 32],
            resource_type.as_str(),
            crate::rpc::AptosResource { data: vec![0u8; 8] },
        );

        let rpc = Box::new(mock);
        let adapter = AptosAnchorLayer::from_config(config.clone(), rpc).unwrap();

        // Create a seal
        let seal = AptosSealRef::new([1u8; 32], resource_type.clone(), 0);
        let commitment = Hash::new([1u8; 32]);
        let result = adapter.publish(commitment, seal);
        assert!(result.is_ok());
    }

    #[test]
    fn test_publish_seal_replay() {
        let config = AptosConfig::default();
        let mock = crate::rpc::MockAptosRpc::new(5000);

        // Register the seal resource in the mock
        let resource_type = format!(
            "{}::csv_seal::{}",
            config.seal_contract.module_address, config.seal_contract.seal_resource
        );
        mock.set_resource(
            [1u8; 32],
            resource_type.as_str(),
            crate::rpc::AptosResource { data: vec![0u8; 8] },
        );

        let rpc = Box::new(mock);
        let adapter = AptosAnchorLayer::from_config(config.clone(), rpc).unwrap();

        let seal = AptosSealRef::new([1u8; 32], resource_type.clone(), 0);
        let commitment = Hash::new([1u8; 32]);
        adapter.publish(commitment, seal.clone()).unwrap();

        // Try to publish again with same seal
        let commitment2 = Hash::new([2u8; 32]);
        let result = adapter.publish(commitment2, seal);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_aptos_address() {
        let addr = parse_aptos_address("0x1").unwrap();
        assert_eq!(addr[31], 1);
        for i in 0..31 {
            assert_eq!(addr[i], 0);
        }
    }

    #[test]
    fn test_parse_aptos_address_full() {
        let full = "0xdeadbeef00000000000000000000000000000000000000000000000000000001";
        let addr = parse_aptos_address(full).unwrap();
        assert_eq!(addr[0], 0xDE);
        assert_eq!(addr[1], 0xAD);
        assert_eq!(addr[31], 0x01);
    }
}