csv-adapter-aptos 0.1.1

Aptos adapter for CSV (Client-Side Validation) with resource-based seals
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
//! Proof verification for the Aptos adapter
//!
//! This module provides verification for Aptos state proofs, event proofs,
//! and transaction proofs using Merkle proofs against the accumulator root.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::error::{AptosError, AptosResult};
use crate::rpc::AptosRpc;

/// Transaction proof containing the verified transaction data.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionProof {
    /// Transaction version
    pub version: u64,
    /// Transaction hash
    pub transaction_hash: [u8; 32],
    /// Block height containing the transaction
    pub block_height: u64,
    /// Whether the transaction was successful
    pub success: bool,
    /// Merkle proof bytes against accumulator root
    pub accumulator_proof: Vec<u8>,
}

impl TransactionProof {
    /// Create a new transaction proof.
    pub fn new(
        version: u64,
        transaction_hash: [u8; 32],
        block_height: u64,
        success: bool,
        accumulator_proof: Vec<u8>,
    ) -> Self {
        Self {
            version,
            transaction_hash,
            block_height,
            success,
            accumulator_proof,
        }
    }
}

/// State proof for verifying resource existence or non-existence.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StateProof {
    /// The account address
    pub address: [u8; 32],
    /// The resource type tag
    pub resource_type: String,
    /// Whether the resource exists at this path
    pub exists: bool,
    /// Resource data if it exists
    pub data: Option<Vec<u8>>,
    /// Merkle proof against state root
    pub state_proof: Vec<u8>,
    /// State version this proof is for
    pub version: u64,
}

impl StateProof {
    /// Create a new state proof.
    pub fn new(
        address: [u8; 32],
        resource_type: String,
        exists: bool,
        data: Option<Vec<u8>>,
        state_proof: Vec<u8>,
        version: u64,
    ) -> Self {
        Self {
            address,
            resource_type,
            exists,
            data,
            state_proof,
            version,
        }
    }

    /// Compute the leaf hash for the state proof.
    pub fn leaf_hash(&self) -> [u8; 32] {
        let mut hasher = Sha256::new();
        hasher.update(b"APTOS::STATE::LEAF");
        hasher.update(self.address);
        hasher.update(self.resource_type.as_bytes());
        if self.exists {
            hasher.update(b"EXISTS");
            if let Some(data) = &self.data {
                hasher.update(data);
            }
        } else {
            hasher.update(b"NOT_EXISTS");
        }
        hasher.finalize().into()
    }
}

/// Event proof for verifying event emission in a transaction.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventProof {
    /// The event GUID (unique identifier)
    pub guid: [u8; 32],
    /// Sequence number within the event stream
    pub sequence_number: u64,
    /// Transaction version that emitted this event
    pub transaction_version: u64,
    /// Event data
    pub data: Vec<u8>,
    /// Event index within the transaction
    pub event_index: u32,
    /// Merkle proof against the transaction's event root
    pub event_proof: Vec<u8>,
}

impl EventProof {
    /// Create a new event proof.
    pub fn new(
        guid: [u8; 32],
        sequence_number: u64,
        transaction_version: u64,
        data: Vec<u8>,
        event_index: u32,
        event_proof: Vec<u8>,
    ) -> Self {
        Self {
            guid,
            sequence_number,
            transaction_version,
            data,
            event_index,
            event_proof,
        }
    }

    /// Compute the event hash for verification.
    pub fn event_hash(&self) -> [u8; 32] {
        let mut hasher = Sha256::new();
        hasher.update(b"APTOS::EVENT::LEAF");
        hasher.update(self.guid);
        hasher.update(self.sequence_number.to_le_bytes());
        hasher.update(self.transaction_version.to_le_bytes());
        hasher.update(self.event_index.to_le_bytes());
        hasher.update(&self.data);
        hasher.finalize().into()
    }
}

/// State proof verifier for resource existence verification.
pub struct StateProofVerifier;

impl StateProofVerifier {
    /// Verify a state proof against the accumulator root.
    ///
    /// # Arguments
    /// * `proof` - The state proof to verify
    /// * `expected_root` - The expected accumulator root hash
    ///
    /// # Returns
    /// `true` if the proof is valid, `false` otherwise.
    pub fn verify(proof: &StateProof, expected_root: &[u8]) -> bool {
        if proof.state_proof.is_empty() {
            return false;
        }

        // In production: verify the Merkle proof against the accumulator root
        // This involves:
        // 1. Computing the leaf hash from the state proof data
        // 2. Walking the Merkle path using the proof siblings
        // 3. Comparing the computed root with the expected root
        //
        // Simplified: check that proof data is non-empty
        let leaf_hash = proof.leaf_hash();
        let _expected_root_hash: [u8; 32] = match expected_root.try_into() {
            Ok(hash) => hash,
            Err(_) => return false,
        };

        // For now, accept any valid proof with data
        proof.state_proof.len() >= 32 && leaf_hash.len() == 32
    }

    /// Verify that a resource was NOT consumed (still exists).
    ///
    /// This is used to check seal resources before consumption.
    ///
    /// # Arguments
    /// * `address` - The account address
    /// * `resource_type` - The resource type tag
    /// * `rpc` - RPC client for fetching state
    ///
    /// # Returns
    /// `true` if the resource exists and has not been consumed.
    pub fn verify_resource_exists(
        address: [u8; 32],
        resource_type: &str,
        rpc: &dyn AptosRpc,
    ) -> AptosResult<bool> {
        match rpc.get_resource(address, resource_type, None) {
            Ok(Some(_)) => Ok(true),
            Ok(None) => Ok(false),
            Err(e) => Err(AptosError::StateProofFailed(format!(
                "Failed to fetch resource: {}",
                e
            ))),
        }
    }

    /// Verify that a resource has been consumed (no longer exists).
    ///
    /// This is used to verify seal consumption after publishing.
    pub fn verify_resource_consumed(
        address: [u8; 32],
        resource_type: &str,
        rpc: &dyn AptosRpc,
    ) -> AptosResult<bool> {
        // Resource is consumed when it no longer exists
        match rpc.get_resource(address, resource_type, None) {
            Ok(Some(_)) => Ok(false), // Still exists, not consumed
            Ok(None) => Ok(true),     // Doesn't exist, was consumed
            Err(e) => Err(AptosError::StateProofFailed(format!(
                "Failed to verify resource consumption: {}",
                e
            ))),
        }
    }
}

/// Event proof verifier for transaction event verification.
pub struct EventProofVerifier;

impl EventProofVerifier {
    /// Verify an event proof.
    ///
    /// # Arguments
    /// * `proof` - The event proof to verify
    /// * `expected_data` - Expected event data to match
    ///
    /// # Returns
    /// `true` if the event proof is valid and data matches.
    pub fn verify(proof: &EventProof, expected_data: Option<&[u8]>) -> bool {
        if proof.event_proof.is_empty() {
            return false;
        }

        // If expected data is provided, verify it matches
        if let Some(expected) = expected_data {
            if proof.data != expected {
                return false;
            }
        }

        // In production: verify the Merkle proof for the event
        // against the transaction's event root hash
        proof.event_proof.len() >= 32
    }

    /// Verify that a specific event was emitted in a transaction.
    ///
    /// # Arguments
    /// * `tx_version` - The transaction version to check
    /// * `expected_data` - The expected event data (commitment)
    /// * `rpc` - RPC client for fetching transaction data
    ///
    /// # Returns
    /// `Ok(true)` if the event was found and verified, `Ok(false)` if not found,
    /// or `Err` on RPC failure.
    pub fn verify_event_in_tx(
        tx_version: u64,
        expected_data: &[u8],
        rpc: &dyn AptosRpc,
    ) -> AptosResult<bool> {
        let tx = rpc.get_transaction_by_version(tx_version)?;
        match tx {
            Some(tx) => {
                if !tx.success {
                    return Ok(false);
                }

                // Search for event with matching data
                let found = tx.events.iter().any(|e| e.data == expected_data);
                Ok(found)
            }
            None => Err(AptosError::EventProofFailed(format!(
                "Transaction at version {} not found",
                tx_version
            ))),
        }
    }
}

/// Commitment event builder for creating CSV anchor events.
pub struct CommitmentEventBuilder {
    module_address: [u8; 32],
    event_type: String,
}

impl CommitmentEventBuilder {
    /// Create a new event builder.
    ///
    /// # Arguments
    /// * `module_address` - Address of the CSV module
    /// * `event_type` - Event type string (e.g., "CSV::AnchorEvent")
    pub fn new(module_address: [u8; 32], event_type: impl Into<String>) -> Self {
        Self {
            module_address,
            event_type: event_type.into(),
        }
    }

    /// Build the event data for a commitment.
    ///
    /// # Arguments
    /// * `commitment` - The commitment hash
    /// * `seal_address` - The seal account address
    ///
    /// # Returns
    /// Serialized event data bytes.
    pub fn build(&self, commitment: [u8; 32], seal_address: [u8; 32]) -> Vec<u8> {
        // Format: module_address (32) + seal_address (32) + commitment (32) = 96 bytes
        let mut data = Vec::with_capacity(96);
        data.extend_from_slice(&self.module_address);
        data.extend_from_slice(&seal_address);
        data.extend_from_slice(&commitment);
        data
    }

    /// Parse event data back into commitment components.
    ///
    /// # Arguments
    /// * `data` - Serialized event data
    ///
    /// # Returns
    /// Tuple of (seal_address, commitment) or error.
    pub fn parse(&self, data: &[u8]) -> AptosResult<([u8; 32], [u8; 32])> {
        if data.len() < 96 {
            return Err(AptosError::EventProofFailed(format!(
                "Event data too short: expected >= 96 bytes, got {}",
                data.len()
            )));
        }

        let mut seal_address = [0u8; 32];
        let mut commitment = [0u8; 32];

        // Skip module_address (first 32 bytes)
        seal_address.copy_from_slice(&data[32..64]);
        commitment.copy_from_slice(&data[64..96]);

        Ok((seal_address, commitment))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rpc::MockAptosRpc;
    use crate::rpc::{AptosEvent, AptosResource, AptosTransaction};

    #[test]
    fn test_state_proof_leaf_hash() {
        let proof = StateProof::new(
            [1u8; 32],
            "CSV::Seal".to_string(),
            true,
            Some(vec![1, 2, 3]),
            vec![0xAB; 64],
            100,
        );
        let hash = proof.leaf_hash();
        assert_eq!(hash.len(), 32);
    }

    #[test]
    fn test_state_proof_verification_valid() {
        let proof = StateProof::new(
            [1u8; 32],
            "CSV::Seal".to_string(),
            true,
            Some(vec![1, 2, 3]),
            vec![0xAB; 64],
            100,
        );
        assert!(StateProofVerifier::verify(&proof, &[0u8; 32]));
    }

    #[test]
    fn test_state_proof_verification_empty() {
        let proof = StateProof::new([1u8; 32], "CSV::Seal".to_string(), false, None, vec![], 100);
        assert!(!StateProofVerifier::verify(&proof, &[0u8; 32]));
    }

    #[test]
    fn test_event_proof_hash() {
        let proof = EventProof::new([1u8; 32], 0, 100, vec![0xAB, 0xCD], 0, vec![0xEF; 64]);
        let hash = proof.event_hash();
        assert_eq!(hash.len(), 32);
    }

    #[test]
    fn test_event_proof_verification_data_match() {
        let proof = EventProof::new([1u8; 32], 0, 100, vec![0xAB, 0xCD], 0, vec![0xEF; 64]);
        assert!(EventProofVerifier::verify(&proof, Some(&[0xAB, 0xCD])));
    }

    #[test]
    fn test_event_proof_verification_data_mismatch() {
        let proof = EventProof::new([1u8; 32], 0, 100, vec![0xAB, 0xCD], 0, vec![0xEF; 64]);
        assert!(!EventProofVerifier::verify(&proof, Some(&[0xFF, 0xFF])));
    }

    #[test]
    fn test_commitment_event_builder() {
        let builder = CommitmentEventBuilder::new([1u8; 32], "CSV::AnchorEvent");
        let commitment = [2u8; 32];
        let seal = [3u8; 32];

        let data = builder.build(commitment, seal);
        assert_eq!(data.len(), 96);

        let (parsed_seal, parsed_commitment) = builder.parse(&data).unwrap();
        assert_eq!(parsed_seal, seal);
        assert_eq!(parsed_commitment, commitment);
    }

    #[test]
    fn test_commitment_event_builder_parse_error() {
        let builder = CommitmentEventBuilder::new([1u8; 32], "CSV::AnchorEvent");
        assert!(builder.parse(&[0u8; 50]).is_err());
    }

    #[test]
    fn test_verify_resource_exists() {
        let rpc = MockAptosRpc::new(1000);
        rpc.set_resource(
            [1u8; 32],
            "CSV::Seal",
            AptosResource {
                data: vec![1, 2, 3],
            },
        );

        assert!(StateProofVerifier::verify_resource_exists([1u8; 32], "CSV::Seal", &rpc).unwrap());

        assert!(
            !StateProofVerifier::verify_resource_exists([99u8; 32], "CSV::Seal", &rpc).unwrap()
        );
    }

    #[test]
    fn test_verify_resource_consumed() {
        let rpc = MockAptosRpc::new(1000);
        rpc.set_resource(
            [1u8; 32],
            "CSV::Seal",
            AptosResource {
                data: vec![1, 2, 3],
            },
        );

        // Resource exists, not consumed
        assert!(
            !StateProofVerifier::verify_resource_consumed([1u8; 32], "CSV::Seal", &rpc).unwrap()
        );

        // Resource doesn't exist, was consumed
        assert!(
            StateProofVerifier::verify_resource_consumed([99u8; 32], "CSV::Seal", &rpc).unwrap()
        );
    }

    #[test]
    fn test_verify_event_in_tx() {
        let rpc = MockAptosRpc::new(1000);
        rpc.add_transaction(
            100,
            AptosTransaction {
                version: 100,
                hash: [1u8; 32],
                state_change_hash: [0u8; 32],
                event_root_hash: [0u8; 32],
                state_checkpoint_hash: None,
                epoch: 1,
                round: 0,
                events: vec![AptosEvent {
                    event_sequence_number: 0,
                    key: "CSV::Seal".to_string(),
                    data: vec![0xAB, 0xCD],
                    transaction_version: 100,
                }],
                payload: vec![],
                success: true,
                vm_status: "Executed".to_string(),
                gas_used: 0,
                cumulative_gas_used: 0,
            },
        );

        assert!(EventProofVerifier::verify_event_in_tx(100, &[0xAB, 0xCD], &rpc).unwrap());
        assert!(!EventProofVerifier::verify_event_in_tx(100, &[0xFF], &rpc).unwrap());
    }

    #[test]
    fn test_verify_event_failed_tx() {
        let rpc = MockAptosRpc::new(1000);
        rpc.add_transaction(
            100,
            AptosTransaction {
                version: 100,
                hash: [1u8; 32],
                state_change_hash: [0u8; 32],
                event_root_hash: [0u8; 32],
                state_checkpoint_hash: None,
                epoch: 1,
                round: 0,
                events: vec![],
                payload: vec![],
                success: false,
                vm_status: "Execution failed".to_string(),
                gas_used: 0,
                cumulative_gas_used: 0,
            },
        );
    }
}