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
use derive_more::From;
use derive_more::Into;
use std::num::Wrapping;
use std::ops::Bound;
use std::ops::RangeBounds;
#[cfg(test)]
use std::ops::RangeInclusive;
#[cfg(test)]
mod tests;
mod dht_arc_set;
pub use dht_arc_set::{ArcInterval, DhtArcSet};
mod dht_arc_bucket;
pub use dht_arc_bucket::*;
#[cfg(any(test, feature = "test_utils"))]
pub mod gaps;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, From, Into)]
pub struct DhtLocation(pub Wrapping<u32>);
pub const MAX_HALF_LENGTH: u32 = (u32::MAX / 2) + 1 + 1;
const U32_LEN: u64 = u32::MAX as u64 + 1;
const REDUNDANCY_TARGET: usize = 50;
const REDUNDANCY_FLOOR: usize = 20;
const DEFAULT_UPTIME: f64 = 0.5;
pub const MIN_PEERS: usize = (REDUNDANCY_TARGET as f64 / DEFAULT_UPTIME) as usize;
pub const MIN_REDUNDANCY: usize = (REDUNDANCY_FLOOR as f64 / DEFAULT_UPTIME) as usize;
const DELTA_SCALE: f64 = 0.2;
const DELTA_THRESHOLD: f64 = 0.01;
const NOISE_THRESHOLD: f64 = 0.01;
fn clamp(min: f64, max: f64, mut x: f64) -> f64 {
if x < min {
x = min;
}
if x > max {
x = max;
}
x
}
fn coverage_target(est_total_peers: usize) -> f64 {
if est_total_peers <= REDUNDANCY_TARGET {
1.0
} else {
REDUNDANCY_TARGET as f64 / est_total_peers as f64
}
}
fn target(density: PeerDensity) -> f64 {
let est_gap = density.est_gap();
if density.expected_count() < REDUNDANCY_TARGET {
1.0
} else {
let est_gap = clamp(0.0, 1.0, est_gap);
let ideal_target = coverage_target(density.est_total_peers());
let target = est_gap.max(ideal_target);
clamp(0.0, 1.0, target)
}
}
fn converge(current: f64, density: PeerDensity) -> f64 {
let target = target(density);
let delta = target - current;
if delta.abs() < DELTA_THRESHOLD {
current + delta
} else {
current + (delta * DELTA_SCALE)
}
}
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct DhtArc {
pub center_loc: DhtLocation,
pub half_length: u32,
}
impl DhtArc {
pub fn new<I: Into<DhtLocation>>(center_loc: I, half_length: u32) -> Self {
let half_length = std::cmp::min(half_length, MAX_HALF_LENGTH);
Self {
center_loc: center_loc.into(),
half_length,
}
}
pub fn update_length(&mut self, density: PeerDensity) {
self.half_length = (MAX_HALF_LENGTH as f64 * converge(self.coverage(), density)) as u32;
}
pub fn contains<I: Into<DhtLocation>>(&self, other_location: I) -> bool {
let other_location = other_location.into();
let do_hold_something = self.half_length != 0;
let only_hold_self = self.half_length == 1 && self.center_loc == other_location;
let dist_as_array_len = shortest_arc_distance(self.center_loc, other_location.0) + 1;
let within_range = self.half_length > 1 && dist_as_array_len <= self.half_length;
do_hold_something && (only_hold_self || within_range)
}
pub fn interval(&self) -> ArcInterval {
let range = self.range();
match (range.start_bound(), range.end_bound()) {
(Bound::Excluded(_), Bound::Excluded(_)) => ArcInterval::Empty,
(Bound::Included(start), Bound::Included(end)) => ArcInterval::new(*start, *end),
_ => unreachable!(),
}
}
pub fn range(&self) -> ArcRange {
if self.half_length == 0 {
ArcRange {
start: Bound::Excluded(self.center_loc.into()),
end: Bound::Excluded(self.center_loc.into()),
}
} else if self.half_length == 1 {
ArcRange {
start: Bound::Included(self.center_loc.into()),
end: Bound::Included(self.center_loc.into()),
}
} else if self.half_length == MAX_HALF_LENGTH || self.half_length == MAX_HALF_LENGTH - 1 {
ArcRange {
start: Bound::Included(
(self.center_loc.0 - DhtLocation::from(MAX_HALF_LENGTH - 1).0).0,
),
end: Bound::Included(
(self.center_loc.0 + DhtLocation::from(MAX_HALF_LENGTH).0 - Wrapping(2)).0,
),
}
} else {
ArcRange {
start: Bound::Included(
(self.center_loc.0 - DhtLocation::from(self.half_length - 1).0).0,
),
end: Bound::Included(
(self.center_loc.0 + DhtLocation::from(self.half_length).0 - Wrapping(1)).0,
),
}
}
}
pub fn primitive_range_grouped(&self) -> Option<(u32, u32)> {
let ArcRange { start, end } = self.range();
match (start, end) {
(Bound::Included(a), Bound::Included(b)) => Some((a, b)),
(Bound::Excluded(_), Bound::Excluded(_)) => None,
_ => unreachable!(),
}
}
pub fn primitive_range_detached(&self) -> (Option<u32>, Option<u32>) {
self.primitive_range_grouped()
.map(|(a, b)| (Some(a), Some(b)))
.unwrap_or_default()
}
pub fn absolute_length(&self) -> u64 {
self.range().len()
}
pub fn coverage(&self) -> f64 {
self.absolute_length() as f64 / U32_LEN as f64
}
}
impl From<u32> for DhtLocation {
fn from(a: u32) -> Self {
Self(Wrapping(a))
}
}
impl From<DhtLocation> for u32 {
fn from(l: DhtLocation) -> Self {
(l.0).0
}
}
fn shortest_arc_distance<A: Into<DhtLocation>, B: Into<DhtLocation>>(a: A, b: B) -> u32 {
let a = a.into().0;
let b = b.into().0;
std::cmp::min(a - b, b - a).0
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ArcRange {
pub start: Bound<u32>,
pub end: Bound<u32>,
}
impl ArcRange {
pub fn is_empty(&self) -> bool {
matches!((self.start_bound(), self.end_bound()), (Bound::Excluded(a), Bound::Excluded(b)) if a == b)
}
pub fn len(&self) -> u64 {
match (self.start_bound(), self.end_bound()) {
(Bound::Included(start), Bound::Included(end)) if end < start => {
U32_LEN - *start as u64 + *end as u64 + 1
}
(Bound::Included(start), Bound::Included(end)) if start == end => 1,
(Bound::Included(start), Bound::Included(end)) => (end - start) as u64 + 1,
(Bound::Excluded(_), Bound::Excluded(_)) => 0,
_ => unreachable!("Ranges are either completely inclusive or completely exclusive"),
}
}
#[cfg(test)]
fn into_inc(self: ArcRange) -> RangeInclusive<usize> {
match self {
ArcRange {
start: Bound::Included(a),
end: Bound::Included(b),
} if a <= b => RangeInclusive::new(a as usize, b as usize),
arc => panic!(
"This range goes all the way around the arc from {:?} to {:?}",
arc.start_bound(),
arc.end_bound()
),
}
}
}
impl RangeBounds<u32> for ArcRange {
fn start_bound(&self) -> Bound<&u32> {
match &self.start {
Bound::Included(i) => Bound::Included(i),
Bound::Excluded(i) => Bound::Excluded(i),
Bound::Unbounded => unreachable!("No unbounded ranges for arcs"),
}
}
fn end_bound(&self) -> Bound<&u32> {
match &self.end {
Bound::Included(i) => Bound::Included(i),
Bound::Excluded(i) => Bound::Excluded(i),
Bound::Unbounded => unreachable!("No unbounded ranges for arcs"),
}
}
fn contains<U>(&self, _item: &U) -> bool
where
u32: PartialOrd<U>,
U: ?Sized + PartialOrd<u32>,
{
unimplemented!("Contains doesn't make sense for this type of range due to redundant holding near the bounds. Use DhtArc::contains")
}
}
impl std::fmt::Display for DhtArc {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut out = ["_"; 100];
let half_cov = (self.coverage() * 50.0) as isize;
let center = self.center_loc.0 .0 as f64 / U32_LEN as f64;
let center = (center * 100.0) as isize;
for mut i in (center - half_cov)..(center + half_cov) {
if i >= 100 {
i -= 100;
}
if i < 0 {
i += 100;
}
out[i as usize] = "#";
}
out[center as usize] = "|";
let out: String = out.iter().map(|a| a.chars()).flatten().collect();
writeln!(f, "[{}]", out)
}
}