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
|
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize};
/// A pool that collects items and releases them in shuffled batches
/// Used for temporal obfuscation of transaction broadcasts
#[derive(Debug)]
pub struct MixingPool<T> {
/// Items waiting to be released
pool: VecDeque<PoolItem<T>>,
/// Minimum time to collect items before releasing
min_batch_duration: Duration,
/// Maximum time to collect items before forcing release
max_batch_duration: Duration,
/// Maximum number of items in pool before forcing release
max_pool_size: usize,
/// Time when current batch started collecting
batch_start: Option<Instant>,
}
#[derive(Debug, Clone)]
struct PoolItem<T> {
item: T,
#[allow(dead_code)]
added_at: Instant,
}
impl<T> MixingPool<T> {
/// Create a new mixing pool with custom parameters
pub fn new(
min_batch_duration: Duration,
max_batch_duration: Duration,
max_pool_size: usize,
) -> Self {
Self {
pool: VecDeque::new(),
min_batch_duration,
max_batch_duration,
max_pool_size,
batch_start: None,
}
}
/// Create a mixing pool with default parameters (10-30 min batches)
pub fn default() -> Self {
Self::new(
Duration::from_secs(10 * 60), // 10 minutes min
Duration::from_secs(30 * 60), // 30 minutes max
1000, // max 1000 items
)
}
/// Add an item to the mixing pool
pub fn add(&mut self, item: T) {
if self.batch_start.is_none() {
self.batch_start = Some(Instant::now());
}
self.pool.push_back(PoolItem {
item,
added_at: Instant::now(),
});
}
/// Check if pool should release a batch
pub fn should_release(&self) -> bool {
if self.pool.is_empty() {
return false;
}
if let Some(start) = self.batch_start {
let elapsed = start.elapsed();
// Force release if max duration reached
if elapsed >= self.max_batch_duration {
return true;
}
// Force release if pool is full
if self.pool.len() >= self.max_pool_size {
return true;
}
// Release if min duration passed and we have items
if elapsed >= self.min_batch_duration && !self.pool.is_empty() {
return true;
}
}
false
}
/// Release a shuffled batch of all pooled items
pub fn release_batch(&mut self) -> Vec<T> {
let mut items: Vec<T> = self.pool.drain(..).map(|pi| pi.item).collect();
// Shuffle to remove temporal ordering
let mut rng = rand::thread_rng();
items.shuffle(&mut rng);
// Reset batch timer
self.batch_start = None;
items
}
/// Get current pool size
pub fn len(&self) -> usize {
self.pool.len()
}
pub fn is_empty(&self) -> bool {
self.pool.is_empty()
}
/// Get time until next potential release (min batch duration)
pub fn time_until_release(&self) -> Option<Duration> {
self.batch_start.map(|start| {
let elapsed = start.elapsed();
if elapsed >= self.min_batch_duration {
Duration::from_secs(0)
} else {
self.min_batch_duration - elapsed
}
})
}
}
/// Stats about mixing pool performance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MixingPoolStats {
pub total_items_processed: u64,
pub total_batches_released: u64,
pub avg_batch_size: f64,
pub avg_wait_time_secs: f64,
}
/// Mixing pool with statistics tracking
#[derive(Debug)]
pub struct MixingPoolWithStats<T> {
pool: MixingPool<T>,
stats: MixingPoolStats,
#[allow(dead_code)]
item_wait_times: Vec<Duration>,
}
impl<T> MixingPoolWithStats<T> {
pub fn new(pool: MixingPool<T>) -> Self {
Self {
pool,
stats: MixingPoolStats {
total_items_processed: 0,
total_batches_released: 0,
avg_batch_size: 0.0,
avg_wait_time_secs: 0.0,
},
item_wait_times: Vec::new(),
}
}
pub fn add(&mut self, item: T) {
self.pool.add(item);
}
pub fn should_release(&self) -> bool {
self.pool.should_release()
}
pub fn release_batch(&mut self) -> Vec<T> {
let batch = self.pool.release_batch();
let batch_size = batch.len();
// Update stats
self.stats.total_items_processed += batch_size as u64;
self.stats.total_batches_released += 1;
// Update average batch size
let total_batches = self.stats.total_batches_released as f64;
self.stats.avg_batch_size =
(self.stats.avg_batch_size * (total_batches - 1.0) + batch_size as f64) / total_batches;
batch
}
pub fn get_stats(&self) -> &MixingPoolStats {
&self.stats
}
pub fn len(&self) -> usize {
self.pool.len()
}
pub fn is_empty(&self) -> bool {
self.pool.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mixing_pool_add() {
let mut pool = MixingPool::<u32>::default();
pool.add(1);
pool.add(2);
pool.add(3);
assert_eq!(pool.len(), 3);
}
#[test]
fn test_mixing_pool_release() {
let mut pool = MixingPool::<u32>::new(
Duration::from_millis(10),
Duration::from_secs(1),
100,
);
pool.add(1);
pool.add(2);
pool.add(3);
// Should not release immediately
assert!(!pool.should_release());
// Wait for min duration
std::thread::sleep(Duration::from_millis(15));
assert!(pool.should_release());
let batch = pool.release_batch();
assert_eq!(batch.len(), 3);
assert!(pool.is_empty());
}
#[test]
fn test_mixing_pool_shuffle() {
let mut pool = MixingPool::<u32>::new(
Duration::from_millis(10),
Duration::from_secs(1),
100,
);
// Add items in order
for i in 0..100 {
pool.add(i);
}
std::thread::sleep(Duration::from_millis(15));
let batch = pool.release_batch();
// Check all items are present
let mut sorted = batch.clone();
sorted.sort();
assert_eq!(sorted, (0..100).collect::<Vec<_>>());
// Check they were shuffled (very unlikely to be in original order)
assert_ne!(batch, sorted);
}
#[test]
fn test_mixing_pool_max_size() {
let mut pool = MixingPool::<u32>::new(
Duration::from_secs(100), // Long min duration
Duration::from_secs(200),
10, // Small max size
);
// Add items up to max
for i in 0..10 {
pool.add(i);
}
// Should force release due to max size
assert!(pool.should_release());
}
#[test]
fn test_mixing_pool_with_stats() {
let pool = MixingPool::<u32>::new(
Duration::from_millis(10),
Duration::from_secs(1),
100,
);
let mut pool_with_stats = MixingPoolWithStats::new(pool);
for i in 0..5 {
pool_with_stats.add(i);
}
std::thread::sleep(Duration::from_millis(15));
pool_with_stats.release_batch();
let stats = pool_with_stats.get_stats();
assert_eq!(stats.total_items_processed, 5);
assert_eq!(stats.total_batches_released, 1);
assert_eq!(stats.avg_batch_size, 5.0);
}
}
|