exochain-dag 0.2.0-beta

EXOCHAIN append-only DAG with BFT consensus and Merkle structures
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Validated persistent-store DAG append with Byzantine clock defense.
//!
//! Extends the in-memory [`dag::append`](crate::dag::append) with:
//! - Validation-time skew enforcement (±500ms tolerance)
//! - HLC causality validation (node timestamp must strictly exceed all parents)
//! - Stored-node integrity verification (hash recomputation)
//!
//! These checks implement the normative HLC check (EXOCHAIN Specification v2.2): event > parent,
//! preventing Byzantine clock manipulation in the trust fabric.

use exo_core::{
    crypto,
    types::{Hash256, Timestamp},
};

use crate::{
    consensus::PublicKeyResolver,
    dag::compute_node_hash,
    error::{DagError, Result},
    store::DagStore,
};

/// Maximum allowed clock skew between a node and validation time (500ms).
///
/// Nodes claiming timestamps more than this far ahead of the caller-supplied
/// validation timestamp are rejected as potential Byzantine clock manipulation.
const MAX_CLOCK_SKEW_MS: u64 = 500;

/// Validate and append a DAG node to persistent storage.
///
/// Performs three checks beyond basic structure:
/// 1. **Validation-time skew**: reject nodes with timestamps too far in the future
/// 2. **HLC causality**: node timestamp must strictly exceed all parent timestamps
/// 3. **Parent existence**: all parents must exist in the store
///
/// This is the normative append path for persistent deployments (EXOCHAIN Specification v2.2).
/// The in-memory [`dag::append`](crate::dag::append) handles local construction;
/// this function handles validation for nodes received from external sources.
pub async fn validated_append(
    store: &mut impl DagStore,
    node: crate::dag::DagNode,
    validation_time: Timestamp,
    public_keys: &impl PublicKeyResolver,
) -> Result<()> {
    // 1. Validation-time skew check: reject future-dated nodes
    if node.timestamp.physical_ms > 0 {
        let validation_ms = validation_time.physical_ms;
        if node.timestamp.physical_ms > validation_ms.saturating_add(MAX_CLOCK_SKEW_MS) {
            return Err(DagError::StoreError(format!(
                "clock skew: node timestamp {} exceeds validation timestamp {} + {}ms tolerance",
                node.timestamp.physical_ms, validation_ms, MAX_CLOCK_SKEW_MS
            )));
        }
    }

    // 2. Parent existence & HLC causality
    for parent_hash in &node.parents {
        let parent = store
            .get(parent_hash)
            .await?
            .ok_or(DagError::ParentNotFound(*parent_hash))?;

        // Normative HLC Check: node timestamp must strictly exceed parent
        if node.timestamp <= parent.timestamp {
            return Err(DagError::StoreError(format!(
                "causality violation: node timestamp {:?} <= parent timestamp {:?}",
                node.timestamp, parent.timestamp
            )));
        }
    }

    // 3. Creator signature verification. External append must prove that
    // creator_did controls the key configured for this DAG node signer.
    verify_node_creator_signature(&node, public_keys)?;

    // 4. Persist
    store.put(node).await
}

/// Verify a DAG node's canonical identity and creator signature.
///
/// This is intentionally resolver-based: a DID alone does not contain enough
/// public-key material to prove authorship. Callers handling external DAG
/// input must supply a governance/identity backed key resolver and fail closed
/// when a creator key is unknown.
pub fn verify_node_creator_signature(
    node: &crate::dag::DagNode,
    public_keys: &impl PublicKeyResolver,
) -> Result<()> {
    let mut sorted_parents = node.parents.clone();
    sorted_parents.sort();
    sorted_parents.dedup();
    if sorted_parents != node.parents {
        return Err(DagError::InvalidSignature(node.hash));
    }

    let expected_hash = compute_node_hash(
        &node.parents,
        &node.payload_hash,
        &node.creator_did,
        &node.timestamp,
    )?;
    if expected_hash != node.hash {
        return Err(DagError::InvalidSignature(node.hash));
    }

    let Some(public_key) = public_keys.resolve(&node.creator_did) else {
        return Err(DagError::InvalidSignature(node.hash));
    };
    if !crypto::verify(node.hash.as_bytes(), &node.signature, &public_key) {
        return Err(DagError::InvalidSignature(node.hash));
    }
    Ok(())
}

/// Verify integrity of a stored node: check that its hash is correctly
/// computed and all parents exist in the store.
///
/// Returns `Ok(true)` if the node passes all integrity checks,
/// `Ok(false)` if any check fails (hash mismatch or missing parent),
/// and `Err` if the node itself is not found.
pub async fn verify_stored_integrity(store: &impl DagStore, hash: &Hash256) -> Result<bool> {
    let node = match store.get(hash).await? {
        Some(n) => n,
        None => return Err(DagError::NodeNotFound(*hash)),
    };

    // Check all parents exist
    for parent in &node.parents {
        if !store.contains(parent).await? {
            return Ok(false);
        }
    }

    // Recompute hash and compare
    let recomputed = compute_node_hash(
        &node.parents,
        &node.payload_hash,
        &node.creator_did,
        &node.timestamp,
    )?;

    Ok(recomputed == node.hash)
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use exo_core::{
        crypto::KeyPair,
        types::{Did, PublicKey, Signature, Timestamp},
    };

    use super::*;
    use crate::{
        dag::{Dag, DagNode, DeterministicDagClock, append},
        store::MemoryStore,
    };

    fn test_did() -> Did {
        Did::new("did:exo:test").expect("valid")
    }

    type SignFn = Box<dyn Fn(&[u8]) -> Signature>;

    fn test_keypair() -> KeyPair {
        KeyPair::from_secret_bytes([0xD5; 32]).expect("valid test secret key")
    }

    fn test_public_key() -> PublicKey {
        *test_keypair().public_key()
    }

    fn test_resolver() -> impl PublicKeyResolver {
        let did = test_did();
        let public_key = test_public_key();
        move |candidate: &Did| {
            if candidate == &did {
                Some(public_key)
            } else {
                None
            }
        }
    }

    fn make_sign_fn() -> SignFn {
        let keypair = test_keypair();
        Box::new(move |data: &[u8]| keypair.sign(data))
    }

    fn make_test_node() -> DagNode {
        let mut dag = Dag::new();
        let mut clock = DeterministicDagClock::new();
        let creator = test_did();
        let sign_fn = make_sign_fn();
        append(&mut dag, &[], b"genesis", &creator, &*sign_fn, &mut clock).expect("genesis")
    }

    fn make_child_node(parent: &DagNode) -> DagNode {
        let mut dag = Dag::new();
        let mut clock = DeterministicDagClock::new();
        let creator = test_did();
        let sign_fn = make_sign_fn();

        // Insert parent first so we can create a child
        let _g =
            append(&mut dag, &[], b"genesis", &creator, &*sign_fn, &mut clock).expect("genesis");

        // Build child manually with proper parent reference
        let payload_hash = Hash256::digest(b"child-payload");
        let timestamp = Timestamp::new(
            parent.timestamp.physical_ms + 1,
            parent.timestamp.logical + 1,
        );
        let hash = compute_node_hash(&[parent.hash], &payload_hash, &creator, &timestamp).unwrap();
        let signature = (*sign_fn)(hash.as_bytes());

        DagNode {
            hash,
            parents: vec![parent.hash],
            payload_hash,
            creator_did: creator,
            timestamp,
            signature,
        }
    }

    fn make_node_at(timestamp: Timestamp) -> DagNode {
        let creator = test_did();
        let payload_hash = Hash256::digest(b"timestamped-node");
        let hash = compute_node_hash(&[], &payload_hash, &creator, &timestamp).unwrap();
        let sign_fn = make_sign_fn();
        let signature = (*sign_fn)(hash.as_bytes());

        DagNode {
            hash,
            parents: Vec::new(),
            payload_hash,
            creator_did: creator,
            timestamp,
            signature,
        }
    }

    fn validation_time_for(node: &DagNode) -> Timestamp {
        Timestamp::new(
            node.timestamp.physical_ms.saturating_add(MAX_CLOCK_SKEW_MS),
            node.timestamp.logical,
        )
    }

    #[test]
    fn validated_append_has_no_internal_wall_clock() {
        let source = include_str!("append.rs");
        let system_time_pattern = format!("{}{}", "SystemTime::", "now()");
        let unix_epoch_pattern = format!("{}{}", "UNIX_", "EPOCH");

        assert!(
            !source.contains(&system_time_pattern),
            "validated_append must receive caller-supplied validation time"
        );
        assert!(
            !source.contains(&unix_epoch_pattern),
            "validated_append must not derive validation time from the wall clock"
        );
    }

    #[tokio::test]
    async fn validated_append_success() {
        let mut store = MemoryStore::new();
        let genesis = make_test_node();
        store.put(genesis.clone()).await.expect("put genesis");

        let child = make_child_node(&genesis);
        let resolver = test_resolver();
        validated_append(
            &mut store,
            child.clone(),
            validation_time_for(&child),
            &resolver,
        )
        .await
        .expect("validated append");

        assert!(store.contains(&child.hash).await.expect("contains"));
    }

    #[tokio::test]
    async fn validated_append_missing_parent() {
        let mut store = MemoryStore::new();
        // Don't put the parent in the store
        let genesis = make_test_node();
        let child = make_child_node(&genesis);

        let resolver = test_resolver();
        let err = validated_append(
            &mut store,
            child.clone(),
            validation_time_for(&child),
            &resolver,
        )
        .await
        .unwrap_err();
        assert!(matches!(err, DagError::ParentNotFound(_)));
    }

    #[tokio::test]
    async fn validated_append_rejects_forged_external_signature() {
        let mut store = MemoryStore::new();
        let genesis = make_test_node();
        store.put(genesis.clone()).await.expect("put genesis");

        let mut child = make_child_node(&genesis);
        child.signature = Signature::from_bytes([0u8; 64]);

        let resolver = test_resolver();
        let err = validated_append(
            &mut store,
            child.clone(),
            validation_time_for(&child),
            &resolver,
        )
        .await
        .unwrap_err();

        assert!(
            matches!(err, DagError::InvalidSignature(hash) if hash == child.hash),
            "external DAG append must reject forged node signatures, got: {err:?}"
        );
        assert!(
            !store.contains(&child.hash).await.expect("contains"),
            "forged external node must not be persisted"
        );
    }

    #[tokio::test]
    async fn validated_append_rejects_mismatched_canonical_hash() {
        let mut store = MemoryStore::new();
        let genesis = make_test_node();
        store.put(genesis.clone()).await.expect("put genesis");

        let mut child = make_child_node(&genesis);
        child.payload_hash = Hash256::digest(b"tampered");

        let resolver = test_resolver();
        let err = validated_append(
            &mut store,
            child.clone(),
            validation_time_for(&child),
            &resolver,
        )
        .await
        .unwrap_err();

        assert!(
            matches!(err, DagError::InvalidSignature(hash) if hash == child.hash),
            "external DAG append must reject nodes whose hash does not match canonical fields, got: {err:?}"
        );
        assert!(!store.contains(&child.hash).await.expect("contains"));
    }

    #[tokio::test]
    async fn validated_append_rejects_unknown_creator_key() {
        let mut store = MemoryStore::new();
        let genesis = make_test_node();
        store.put(genesis.clone()).await.expect("put genesis");

        let child = make_child_node(&genesis);
        let unknown_key_resolver = |_did: &Did| -> Option<PublicKey> { None };
        let err = validated_append(
            &mut store,
            child.clone(),
            validation_time_for(&child),
            &unknown_key_resolver,
        )
        .await
        .unwrap_err();

        assert!(
            matches!(err, DagError::InvalidSignature(hash) if hash == child.hash),
            "external DAG append must fail closed without a creator public key, got: {err:?}"
        );
        assert!(!store.contains(&child.hash).await.expect("contains"));
    }

    #[tokio::test]
    async fn validated_append_causality_violation() {
        let mut store = MemoryStore::new();
        let genesis = make_test_node();
        store.put(genesis.clone()).await.expect("put genesis");

        // Create a child with timestamp <= parent (causality violation)
        let creator = test_did();
        let payload_hash = Hash256::digest(b"bad-child");
        let timestamp = Timestamp::new(0, 0); // Before genesis
        let hash = compute_node_hash(&[genesis.hash], &payload_hash, &creator, &timestamp).unwrap();
        let sign_fn = make_sign_fn();
        let signature = (*sign_fn)(hash.as_bytes());

        let bad_child = DagNode {
            hash,
            parents: vec![genesis.hash],
            payload_hash,
            creator_did: creator,
            timestamp,
            signature,
        };

        let resolver = test_resolver();
        let err = validated_append(
            &mut store,
            bad_child.clone(),
            validation_time_for(&bad_child),
            &resolver,
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, DagError::StoreError(ref msg) if msg.contains("causality")),
            "expected causality violation, got: {err:?}"
        );
    }

    #[tokio::test]
    async fn validated_append_rejects_node_after_supplied_validation_time() {
        let mut store = MemoryStore::new();
        let node = make_node_at(Timestamp::new(2_001, 0));

        let resolver = test_resolver();
        let err = validated_append(&mut store, node, Timestamp::new(1_500, 0), &resolver)
            .await
            .unwrap_err();

        assert!(
            matches!(
                err,
                DagError::StoreError(ref msg)
                    if msg.contains("node timestamp 2001 exceeds validation timestamp 1500 + 500ms tolerance")
            ),
            "expected validation-time skew rejection, got: {err:?}"
        );
    }

    #[tokio::test]
    async fn validated_append_accepts_node_within_supplied_validation_time_tolerance() {
        let mut store = MemoryStore::new();
        let node = make_node_at(Timestamp::new(2_000, 0));

        let resolver = test_resolver();
        validated_append(
            &mut store,
            node.clone(),
            Timestamp::new(1_500, 0),
            &resolver,
        )
        .await
        .expect("node inside validation-time tolerance");

        assert!(store.contains(&node.hash).await.expect("contains"));
    }

    #[tokio::test]
    async fn verify_stored_integrity_valid() {
        let mut store = MemoryStore::new();
        let node = make_test_node();
        store.put(node.clone()).await.expect("put");

        assert!(
            verify_stored_integrity(&store, &node.hash)
                .await
                .expect("verify")
        );
    }

    #[tokio::test]
    async fn verify_stored_integrity_tampered_hash() {
        let mut store = MemoryStore::new();
        let mut node = make_test_node();
        let original_hash = node.hash;
        // Tamper: modify payload hash but keep the original node hash
        node.payload_hash = Hash256::digest(b"tampered");
        // Re-insert with original hash (simulating store corruption)
        node.hash = original_hash;
        store.put(node).await.expect("put");

        // Integrity check should detect the hash mismatch
        assert!(
            !verify_stored_integrity(&store, &original_hash)
                .await
                .expect("verify")
        );
    }

    #[tokio::test]
    async fn verify_stored_integrity_not_found() {
        let store = MemoryStore::new();
        let err = verify_stored_integrity(&store, &Hash256::ZERO)
            .await
            .unwrap_err();
        assert!(matches!(err, DagError::NodeNotFound(_)));
    }

    #[tokio::test]
    async fn genesis_node_validated_append() {
        let mut store = MemoryStore::new();
        let genesis = make_test_node();
        // Genesis has no parents — should pass validation
        let resolver = test_resolver();
        validated_append(
            &mut store,
            genesis.clone(),
            validation_time_for(&genesis),
            &resolver,
        )
        .await
        .expect("genesis append");
        assert!(store.contains(&genesis.hash).await.expect("contains"));
    }
}