rings_core/dht/
virtual_node.rs1#![deny(missing_docs)]
2use 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
20pub const MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER: u16 = 256;
22
23pub const DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER: u16 = DEFAULT_FINGER_TABLE_SIZE as u16;
31
32pub const fn default_storage_virtual_positions_per_owner() -> u16 {
34 DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER
35}
36
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub struct VirtualNodeConfig {
40 network_id: u32,
42 positions_per_owner: u16,
44}
45
46impl VirtualNodeConfig {
47 pub const fn disabled() -> Self {
49 Self {
50 network_id: 0,
51 positions_per_owner: 0,
52 }
53 }
54
55 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 pub const fn is_enabled(self) -> bool {
67 self.positions_per_owner > 0
68 }
69
70 pub const fn network_id(self) -> u32 {
72 self.network_id
73 }
74
75 pub const fn positions_per_owner(self) -> u16 {
77 self.positions_per_owner
78 }
79
80 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
96pub struct VirtualNode {
97 pub owner_did: Did,
99 pub vnode_did: Did,
101 pub index: u16,
103}
104
105impl VirtualNode {
106 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#[derive(Clone, Debug, Eq, PartialEq)]
124pub struct StorageVirtualNodes {
125 config: VirtualNodeConfig,
126 owners: BTreeSet<Did>,
127}
128
129impl StorageVirtualNodes {
130 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 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 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 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}