Skip to main content

rings_core/dht/
virtual_node.rs

1#![deny(missing_docs)]
2//! Chord-style virtual positions for storage ownership.
3//!
4//! These positions are not independent signing identities. They are derived
5//! ring locations owned by an authenticated physical DID and are used only by
6//! storage owner selection.
7
8use std::collections::BTreeSet;
9
10use ethereum_types::H160;
11use sha1::Digest;
12use sha1::Sha1;
13
14use crate::dht::topology;
15use crate::dht::Did;
16use crate::dht::DEFAULT_FINGER_TABLE_SIZE;
17
18const VIRTUAL_NODE_DOMAIN: &[u8] = b"rings:vnode";
19
20/// Maximum virtual storage positions derived per physical owner.
21pub const MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER: u16 = 256;
22
23/// Default virtual storage positions derived per physical owner.
24///
25/// The Chord paper recommends mapping each real node to O(log N) virtual nodes.
26/// A joining node does not know the stable network size N before it enters the
27/// DHT, so Rings uses the Chord finger-table width as the network-wide default
28/// O(log N) operating point. Operators can still set this to zero to disable
29/// virtual storage ownership for a network.
30pub const DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER: u16 = DEFAULT_FINGER_TABLE_SIZE as u16;
31
32/// Return the default virtual storage positions derived per physical owner.
33pub const fn default_storage_virtual_positions_per_owner() -> u16 {
34    DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER
35}
36
37/// Configuration for storage virtual nodes.
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub struct VirtualNodeConfig {
40    /// Network namespace mixed into derived virtual positions.
41    network_id: u32,
42    /// Number of virtual positions derived for each physical owner.
43    positions_per_owner: u16,
44}
45
46impl VirtualNodeConfig {
47    /// Disable virtual-node storage ownership.
48    pub const fn disabled() -> Self {
49        Self {
50            network_id: 0,
51            positions_per_owner: 0,
52        }
53    }
54
55    /// Build a virtual-node configuration.
56    ///
57    /// Post: `positions_per_owner <= MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER`.
58    pub const fn new(network_id: u32, positions_per_owner: u16) -> Self {
59        Self {
60            network_id,
61            positions_per_owner: Self::bounded_positions_per_owner(positions_per_owner),
62        }
63    }
64
65    /// Returns whether this configuration enables virtual storage ownership.
66    pub const fn is_enabled(self) -> bool {
67        self.positions_per_owner > 0
68    }
69
70    /// Return the network namespace mixed into derived virtual positions.
71    pub const fn network_id(self) -> u32 {
72        self.network_id
73    }
74
75    /// Return the bounded number of positions derived for each physical owner.
76    pub const fn positions_per_owner(self) -> u16 {
77        self.positions_per_owner
78    }
79
80    /// Returns whether `positions_per_owner` is inside the configured cost bound.
81    pub const fn positions_per_owner_within_limit(positions_per_owner: u16) -> bool {
82        positions_per_owner <= MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER
83    }
84
85    const fn bounded_positions_per_owner(positions_per_owner: u16) -> u16 {
86        if positions_per_owner > MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER {
87            MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER
88        } else {
89            positions_per_owner
90        }
91    }
92}
93
94/// One derived Chord ring position owned by a physical peer.
95#[derive(Clone, Copy, Debug, Eq, PartialEq)]
96pub struct VirtualNode {
97    /// Physical peer DID that signs messages and owns the transport.
98    pub owner_did: Did,
99    /// Derived Chord ring position used for storage ownership.
100    pub vnode_did: Did,
101    /// Owner-local virtual-node index.
102    pub index: u16,
103}
104
105impl VirtualNode {
106    /// Derive one virtual position.
107    pub fn derive(network_id: u32, owner_did: Did, index: u16) -> Self {
108        let mut hasher = Sha1::new();
109        hasher.update(VIRTUAL_NODE_DOMAIN);
110        hasher.update(network_id.to_be_bytes());
111        hasher.update(owner_did.as_bytes());
112        hasher.update(index.to_be_bytes());
113        let bytes: [u8; 20] = hasher.finalize().into();
114        Self {
115            owner_did,
116            vnode_did: Did::from(H160::from(bytes)),
117            index,
118        }
119    }
120}
121
122/// Storage-owner registry for derived virtual positions.
123#[derive(Clone, Debug, Eq, PartialEq)]
124pub struct StorageVirtualNodes {
125    config: VirtualNodeConfig,
126    owners: BTreeSet<Did>,
127}
128
129impl StorageVirtualNodes {
130    /// The registry of the physical owners currently visible to storage routing.
131    ///
132    /// Post: with virtual nodes disabled the registry is empty, so every key
133    /// falls back to plain Chord placement.
134    pub fn from_owners(config: VirtualNodeConfig, owners: impl IntoIterator<Item = Did>) -> Self {
135        let owners = if config.is_enabled() {
136            owners.into_iter().collect()
137        } else {
138            BTreeSet::new()
139        };
140        Self { config, owners }
141    }
142
143    /// Return all virtual positions for `owner_did`.
144    pub fn positions_for_owner(&self, owner_did: Did) -> Vec<VirtualNode> {
145        if !self.owners.contains(&owner_did) {
146            return Vec::new();
147        }
148        self.derive_owner_positions(owner_did)
149    }
150
151    /// Return all registered virtual positions.
152    pub fn positions(&self) -> Vec<VirtualNode> {
153        let mut positions = Vec::new();
154        for owner in self.owners.iter().copied() {
155            positions.extend(self.derive_owner_positions(owner));
156        }
157        positions.sort_by_key(|position| (position.vnode_did, position.owner_did, position.index));
158        positions
159    }
160
161    /// Resolve the physical owner responsible for `key`.
162    ///
163    /// This uses Chord successor ownership: the selected virtual position is
164    /// the registered position with minimum clockwise distance from `key`.
165    pub fn owner_for_key(&self, key: Did) -> Option<Did> {
166        self.positions()
167            .into_iter()
168            .min_by(|left, right| {
169                topology::dist(key, left.vnode_did)
170                    .cmp(&topology::dist(key, right.vnode_did))
171                    .then_with(|| left.owner_did.cmp(&right.owner_did))
172                    .then_with(|| left.index.cmp(&right.index))
173            })
174            .map(|position| position.owner_did)
175    }
176
177    fn derive_owner_positions(&self, owner_did: Did) -> Vec<VirtualNode> {
178        (0..self.config.positions_per_owner())
179            .map(|index| VirtualNode::derive(self.config.network_id(), owner_did, index))
180            .collect()
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn test_virtual_node_derivation_is_domain_separated_by_network() {
190        let owner = Did::from(42u32);
191        let first = VirtualNode::derive(7, owner, 0);
192        let repeated = VirtualNode::derive(7, owner, 0);
193        let other_network = VirtualNode::derive(8, owner, 0);
194
195        assert_eq!(first, repeated);
196        assert_ne!(first.vnode_did, owner);
197        assert_ne!(first.vnode_did, other_network.vnode_did);
198    }
199
200    #[test]
201    fn test_virtual_node_config_caps_positions_at_cost_bound() {
202        let config =
203            VirtualNodeConfig::new(1, MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER.saturating_add(1));
204
205        assert_eq!(
206            config.positions_per_owner(),
207            MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER
208        );
209    }
210
211    #[test]
212    fn test_storage_virtual_nodes_resolve_owner_from_virtual_position() -> crate::error::Result<()>
213    {
214        let owner_a = Did::from(10u32);
215        let owner_b = Did::from(20u32);
216        let registry =
217            StorageVirtualNodes::from_owners(VirtualNodeConfig::new(1, 2), [owner_a, owner_b]);
218
219        let owner_b_position = registry
220            .positions_for_owner(owner_b)
221            .into_iter()
222            .next()
223            .map(|position| position.vnode_did)
224            .ok_or_else(|| {
225                crate::error::Error::InvalidMessage(
226                    "owner should have virtual positions".to_string(),
227                )
228            })?;
229
230        assert_eq!(registry.owner_for_key(owner_b_position), Some(owner_b));
231        Ok(())
232    }
233
234    #[test]
235    fn test_storage_virtual_nodes_resolve_successor_owner_for_interval_key(
236    ) -> crate::error::Result<()> {
237        let owners = [Did::from(10u32), Did::from(20u32), Did::from(30u32)];
238        let registry = StorageVirtualNodes::from_owners(VirtualNodeConfig::new(1, 2), owners);
239        let positions = registry.positions();
240
241        let Some((left, successor)) =
242            positions
243                .iter()
244                .zip(positions.iter().cycle().skip(1))
245                .find(|(left, successor)| {
246                    let key = left.vnode_did + Did::from(1u32);
247                    key != successor.vnode_did
248                })
249        else {
250            return Err(crate::error::Error::InvalidMessage(
251                "expected a non-empty virtual interval".to_string(),
252            ));
253        };
254
255        let key = left.vnode_did + Did::from(1u32);
256        assert_eq!(registry.owner_for_key(key), Some(successor.owner_did));
257        Ok(())
258    }
259}