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
//! Hybrid Logical Clocks and Federation Time Semantics
//!
//! Provides tracking for temporal causal ordering without requiring full
//! vector clocks, scaling to large federations with bounded drift policies.
use core::cmp::Ordering;
use serde::{Deserialize, Serialize};
/// A Hybrid Logical Clock (HLC) combining logical causal progression with
/// signed physical timestamps for drift/skew tracking.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct HybridLogicalClock {
/// Incremented on every causal event (the Lamport component).
pub logical_counter: u64,
/// The physical wall-clock time observed by the node at event creation (Unix seconds).
pub physical_timestamp: u64,
/// Cryptographic signature of `(logical_counter || physical_timestamp)` by the issuing verifier.
#[serde(with = "serde_bytes")]
pub signature: Vec<u8>,
}
impl PartialOrd for HybridLogicalClock {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for HybridLogicalClock {
fn cmp(&self, other: &Self) -> Ordering {
// Causality is strictly determined by the logical counter first.
match self.logical_counter.cmp(&other.logical_counter) {
Ordering::Equal => self.physical_timestamp.cmp(&other.physical_timestamp),
other_ordering => other_ordering,
}
}
}
impl HybridLogicalClock {
/// Evaluates if an observed physical time from another clock exceeds
/// the maximum allowable drift (skew limit).
#[must_use]
pub fn exceeds_skew(&self, other: &Self, max_skew_seconds: u64) -> bool {
let diff = self.physical_timestamp.abs_diff(other.physical_timestamp);
diff > max_skew_seconds
}
}
/// Defines federation-wide temporal boundaries.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoundedTimeSkew {
/// Maximum allowed difference between two nodes' physical timestamps
/// in the same causal event window.
pub max_drift_seconds: u64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hlc_ordering() {
let a = HybridLogicalClock {
logical_counter: 1,
physical_timestamp: 1000,
signature: vec![],
};
let b = HybridLogicalClock {
logical_counter: 2,
physical_timestamp: 900,
signature: vec![],
};
// Even though b is physically older, it is logically newer.
assert!(a < b);
let c = HybridLogicalClock {
logical_counter: 1,
physical_timestamp: 1001,
signature: vec![],
};
assert!(a < c);
}
#[test]
fn test_skew_enforcement() {
let a = HybridLogicalClock {
logical_counter: 1,
physical_timestamp: 1000,
signature: vec![],
};
let b = HybridLogicalClock {
logical_counter: 2,
physical_timestamp: 1050,
signature: vec![],
};
assert!(!a.exceeds_skew(&b, 60)); // 50 <= 60
assert!(a.exceeds_skew(&b, 40)); // 50 > 40
}
}