0eb2e8e7b9a21ea9d8444062efa15c9887644b1e
[dnsseed-rust] / src / datastore.rs
1 use std::{cmp, mem};
2 use std::collections::{HashSet, HashMap, hash_map};
3 use std::sync::{Arc, RwLock};
4 use std::net::SocketAddr;
5 use std::time::{Duration, Instant};
6 use std::io::{BufRead, BufReader};
7
8 use bitcoin::network::address::Address;
9
10 use rand::thread_rng;
11 use rand::seq::{SliceRandom, IteratorRandom};
12
13 use tokio::prelude::*;
14 use tokio::fs::File;
15 use tokio::io::write_all;
16
17 use regex::Regex;
18
19 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
20 pub enum AddressState {
21         Untested,
22         LowBlockCount,
23         HighBlockCount,
24         LowVersion,
25         BadVersion,
26         NotFullNode,
27         ProtocolViolation,
28         Timeout,
29         TimeoutDuringRequest,
30         TimeoutAwaitingAddr,
31         TimeoutAwaitingBlock,
32         Good,
33         WasGood,
34 }
35
36 impl AddressState {
37         pub fn from_num(num: u8) -> Option<AddressState> {
38                 match num {
39                         0x0 => Some(AddressState::Untested),
40                         0x1 => Some(AddressState::LowBlockCount),
41                         0x2 => Some(AddressState::HighBlockCount),
42                         0x3 => Some(AddressState::LowVersion),
43                         0x4 => Some(AddressState::BadVersion),
44                         0x5 => Some(AddressState::NotFullNode),
45                         0x6 => Some(AddressState::ProtocolViolation),
46                         0x7 => Some(AddressState::Timeout),
47                         0x8 => Some(AddressState::TimeoutDuringRequest),
48                         0x9 => Some(AddressState::TimeoutAwaitingAddr),
49                         0xa => Some(AddressState::TimeoutAwaitingBlock),
50                         0xb => Some(AddressState::Good),
51                         0xc => Some(AddressState::WasGood),
52                         _   => None,
53                 }
54         }
55
56         pub fn to_num(&self) -> u8 {
57                 match *self {
58                         AddressState::Untested => 0,
59                         AddressState::LowBlockCount => 1,
60                         AddressState::HighBlockCount => 2,
61                         AddressState::LowVersion => 3,
62                         AddressState::BadVersion => 4,
63                         AddressState::NotFullNode => 5,
64                         AddressState::ProtocolViolation => 6,
65                         AddressState::Timeout => 7,
66                         AddressState::TimeoutDuringRequest => 8,
67                         AddressState::TimeoutAwaitingAddr => 9,
68                         AddressState::TimeoutAwaitingBlock => 10,
69                         AddressState::Good => 11,
70                         AddressState::WasGood => 12,
71                 }
72         }
73
74         pub fn to_str(&self) -> &'static str {
75                 match *self {
76                         AddressState::Untested => "Untested",
77                         AddressState::LowBlockCount => "Low Block Count",
78                         AddressState::HighBlockCount => "High Block Count",
79                         AddressState::LowVersion => "Low Version",
80                         AddressState::BadVersion => "Bad Version",
81                         AddressState::NotFullNode => "Not Full Node",
82                         AddressState::ProtocolViolation => "Protocol Violation",
83                         AddressState::Timeout => "Timeout",
84                         AddressState::TimeoutDuringRequest => "Timeout During Request",
85                         AddressState::TimeoutAwaitingAddr => "Timeout Awaiting Addr",
86                         AddressState::TimeoutAwaitingBlock => "Timeout Awaiting Block",
87                         AddressState::Good => "Good",
88                         AddressState::WasGood => "Was Good",
89                 }
90         }
91
92         pub const fn get_count() -> u8 {
93                 13
94         }
95 }
96
97 #[derive(Hash, PartialEq, Eq)]
98 pub enum U64Setting {
99         ConnsPerSec,
100         RunTimeout,
101         WasGoodTimeout,
102         RescanInterval(AddressState),
103         MinProtocolVersion,
104 }
105
106 #[derive(Hash, PartialEq, Eq)]
107 pub enum RegexSetting {
108         SubverRegex,
109 }
110
111 struct Node {
112         last_update: Instant,
113         last_good: Instant, // Ignored unless state is Good or WasGood
114         last_services: u64,
115         state: AddressState,
116 }
117
118 struct Nodes {
119         good_node_services: Vec<HashSet<SocketAddr>>,
120         nodes_to_state: HashMap<SocketAddr, Node>,
121         state_next_scan: Vec<Vec<(Instant, SocketAddr)>>,
122 }
123 struct NodesMutRef<'a> {
124         good_node_services: &'a mut Vec<HashSet<SocketAddr>>,
125         nodes_to_state: &'a mut HashMap<SocketAddr, Node>,
126         state_next_scan: &'a mut Vec<Vec<(Instant, SocketAddr)>>,
127
128 }
129 impl Nodes {
130         fn borrow_mut<'a>(&'a mut self) -> NodesMutRef<'a> {
131                 NodesMutRef {
132                         good_node_services: &mut self.good_node_services,
133                         nodes_to_state: &mut self.nodes_to_state,
134                         state_next_scan: &mut self.state_next_scan,
135                 }
136         }
137 }
138
139 pub struct Store {
140         u64_settings: RwLock<HashMap<U64Setting, u64>>,
141         subver_regex: RwLock<Arc<Regex>>,
142         nodes: RwLock<Nodes>,
143         store: String,
144 }
145
146 impl Store {
147         pub fn new(store: String) -> impl Future<Item=Store, Error=()> {
148                 let settings_future = File::open(store.clone() + "/settings").and_then(|f| {
149                         let mut l = BufReader::new(f).lines();
150                         macro_rules! try_read {
151                                 ($lines: expr, $ty: ty) => { {
152                                         match $lines.next() {
153                                                 Some(line) => match line {
154                                                         Ok(line) => match line.parse::<$ty>() {
155                                                                 Ok(res) => res,
156                                                                 Err(e) => return future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
157                                                         },
158                                                         Err(e) => return future::err(e),
159                                                 },
160                                                 None => return future::err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "")),
161                                         }
162                                 } }
163                         }
164                         let mut u64s = HashMap::with_capacity(AddressState::get_count() as usize + 4);
165                         u64s.insert(U64Setting::ConnsPerSec, try_read!(l, u64));
166                         u64s.insert(U64Setting::RunTimeout, try_read!(l, u64));
167                         u64s.insert(U64Setting::WasGoodTimeout, try_read!(l, u64));
168                         u64s.insert(U64Setting::MinProtocolVersion, try_read!(l, u64));
169                         u64s.insert(U64Setting::RescanInterval(AddressState::Untested), try_read!(l, u64));
170                         u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), try_read!(l, u64));
171                         u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), try_read!(l, u64));
172                         u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), try_read!(l, u64));
173                         u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), try_read!(l, u64));
174                         u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), try_read!(l, u64));
175                         u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), try_read!(l, u64));
176                         u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), try_read!(l, u64));
177                         u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), try_read!(l, u64));
178                         u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingAddr), try_read!(l, u64));
179                         u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingBlock), try_read!(l, u64));
180                         u64s.insert(U64Setting::RescanInterval(AddressState::Good), try_read!(l, u64));
181                         u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), try_read!(l, u64));
182                         future::ok((u64s, try_read!(l, Regex)))
183                 }).or_else(|_| -> future::FutureResult<(HashMap<U64Setting, u64>, Regex), ()> {
184                         let mut u64s = HashMap::with_capacity(15);
185                         u64s.insert(U64Setting::ConnsPerSec, 10);
186                         u64s.insert(U64Setting::RunTimeout, 120);
187                         u64s.insert(U64Setting::WasGoodTimeout, 21600);
188                         u64s.insert(U64Setting::RescanInterval(AddressState::Untested), 0);
189                         u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), 3600);
190                         u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), 7200);
191                         u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), 21600);
192                         u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), 21600);
193                         u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), 86400);
194                         u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), 86400);
195                         u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), 86400);
196                         u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), 21600);
197                         u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingAddr), 1800);
198                         u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingBlock), 3600);
199                         u64s.insert(U64Setting::RescanInterval(AddressState::Good), 1800);
200                         u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), 1800);
201                         u64s.insert(U64Setting::MinProtocolVersion, 70002);
202                         future::ok((u64s, Regex::new(".*").unwrap()))
203                 });
204
205                 macro_rules! nodes_uninitd {
206                         () => { {
207                                 let mut state_vecs = Vec::with_capacity(AddressState::get_count() as usize);
208                                 for _ in 0..AddressState::get_count() {
209                                         state_vecs.push(Vec::new());
210                                 }
211                                 let mut good_node_services = Vec::with_capacity(64);
212                                 for _ in 0..64 {
213                                         good_node_services.push(HashSet::new());
214                                 }
215                                 Nodes {
216                                         good_node_services,
217                                         nodes_to_state: HashMap::new(),
218                                         state_next_scan: state_vecs,
219                                 }
220                         } }
221                 }
222
223                 let nodes_future = File::open(store.clone() + "/nodes").and_then(|f| {
224                         let mut res = nodes_uninitd!();
225                         let l = BufReader::new(f).lines();
226                         for line_res in l {
227                                 let line = match line_res {
228                                         Ok(l) => l,
229                                         Err(_) => return future::ok(res),
230                                 };
231                                 let mut line_iter = line.split(',');
232                                 macro_rules! try_read {
233                                         ($lines: expr, $ty: ty) => { {
234                                                 match $lines.next() {
235                                                         Some(line) => match line.parse::<$ty>() {
236                                                                 Ok(res) => res,
237                                                                 Err(_) => return future::ok(res),
238                                                         },
239                                                         None => return future::ok(res),
240                                                 }
241                                         } }
242                                 }
243                                 let sockaddr = try_read!(line_iter, SocketAddr);
244                                 let state = try_read!(line_iter, u8);
245                                 let last_services = try_read!(line_iter, u64);
246                                 let node = Node {
247                                         state: match AddressState::from_num(state) {
248                                                 Some(v) => v,
249                                                 None => return future::ok(res),
250                                         },
251                                         last_services,
252                                         last_update: Instant::now(),
253                                         last_good: Instant::now(),
254                                 };
255                                 if node.state == AddressState::Good {
256                                         for i in 0..64 {
257                                                 if node.last_services & (1 << i) != 0 {
258                                                         res.good_node_services[i].insert(sockaddr);
259                                                 }
260                                         }
261                                 }
262                                 res.state_next_scan[node.state.to_num() as usize].push((Instant::now(), sockaddr));
263                                 res.nodes_to_state.insert(sockaddr, node);
264                         }
265                         future::ok(res)
266                 }).or_else(|_| -> future::FutureResult<Nodes, ()> {
267                         future::ok(nodes_uninitd!())
268                 });
269                 settings_future.join(nodes_future).and_then(move |((u64_settings, regex), nodes)| {
270                         future::ok(Store {
271                                 u64_settings: RwLock::new(u64_settings),
272                                 subver_regex: RwLock::new(Arc::new(regex)),
273                                 nodes: RwLock::new(nodes),
274                                 store,
275                         })
276                 })
277         }
278
279         pub fn get_u64(&self, setting: U64Setting) -> u64 {
280                 *self.u64_settings.read().unwrap().get(&setting).unwrap()
281         }
282
283         pub fn set_u64(&self, setting: U64Setting, value: u64) {
284                 *self.u64_settings.write().unwrap().get_mut(&setting).unwrap() = value;
285         }
286
287         pub fn get_node_count(&self, state: AddressState) -> usize {
288                 self.nodes.read().unwrap().state_next_scan[state.to_num() as usize].len()
289         }
290
291         pub fn get_regex(&self, _setting: RegexSetting) -> Arc<Regex> {
292                 Arc::clone(&*self.subver_regex.read().unwrap())
293         }
294
295         pub fn set_regex(&self, _setting: RegexSetting, value: Regex) {
296                 *self.subver_regex.write().unwrap() = Arc::new(value);
297         }
298
299         pub fn add_fresh_addrs<I: Iterator<Item=SocketAddr>>(&self, addresses: I) -> u64 {
300                 let mut res = 0;
301                 let mut nodes = self.nodes.write().unwrap();
302                 let cur_time = Instant::now();
303                 for addr in addresses {
304                         match nodes.nodes_to_state.entry(addr.clone()) {
305                                 hash_map::Entry::Vacant(e) => {
306                                         e.insert(Node {
307                                                 state: AddressState::Untested,
308                                                 last_services: 0,
309                                                 last_update: cur_time,
310                                                 last_good: cur_time,
311                                         });
312                                         nodes.state_next_scan[AddressState::Untested.to_num() as usize].push((cur_time, addr));
313                                         res += 1;
314                                 },
315                                 hash_map::Entry::Occupied(_) => {},
316                         }
317                 }
318                 res
319         }
320
321         pub fn add_fresh_nodes(&self, addresses: &Vec<(u32, Address)>) {
322                 self.add_fresh_addrs(addresses.iter().filter_map(|(_, addr)| {
323                         match addr.socket_addr() {
324                                 Ok(socketaddr) => Some(socketaddr),
325                                 Err(_) => None, // TODO: Handle onions
326                         }
327                 }));
328         }
329
330         pub fn set_node_state(&self, addr: SocketAddr, state: AddressState, services: u64) -> AddressState {
331                 let mut nodes_lock = self.nodes.write().unwrap();
332                 let nodes = nodes_lock.borrow_mut();
333                 let now = Instant::now();
334
335                 let state_ref = nodes.nodes_to_state.entry(addr).or_insert(Node {
336                         state: AddressState::Untested,
337                         last_services: 0,
338                         last_update: now,
339                         last_good: now,
340                 });
341                 let ret = state_ref.state;
342                 if (state_ref.state == AddressState::Good || state_ref.state == AddressState::WasGood)
343                                 && state != AddressState::Good
344                                 && state_ref.last_good >= now - Duration::from_secs(self.get_u64(U64Setting::WasGoodTimeout)) {
345                         state_ref.state = AddressState::WasGood;
346                         for i in 0..64 {
347                                 if state_ref.last_services & (1 << i) != 0 {
348                                         nodes.good_node_services[i].remove(&addr);
349                                 }
350                         }
351                         state_ref.last_services = 0;
352                         nodes.state_next_scan[AddressState::WasGood.to_num() as usize].push((now, addr));
353                 } else {
354                         state_ref.state = state;
355                         if state == AddressState::Good {
356                                 for i in 0..64 {
357                                         if services & (1 << i) != 0 && state_ref.last_services & (1 << i) == 0 {
358                                                 nodes.good_node_services[i].insert(addr);
359                                         } else if services & (1 << i) == 0 && state_ref.last_services & (1 << i) != 0 {
360                                                 nodes.good_node_services[i].remove(&addr);
361                                         }
362                                 }
363                                 state_ref.last_services = services;
364                                 state_ref.last_good = now;
365                         }
366                         nodes.state_next_scan[state.to_num() as usize].push((now, addr));
367                 }
368                 state_ref.last_update = now;
369                 ret
370         }
371
372         pub fn save_data(&'static self) -> impl Future<Item=(), Error=()> {
373                 let settings_file = self.store.clone() + "/settings";
374                 let settings_future = File::create(settings_file.clone() + ".tmp").and_then(move |f| {
375                         let settings_string = format!("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
376                                 self.get_u64(U64Setting::ConnsPerSec),
377                                 self.get_u64(U64Setting::RunTimeout),
378                                 self.get_u64(U64Setting::WasGoodTimeout),
379                                 self.get_u64(U64Setting::MinProtocolVersion),
380                                 self.get_u64(U64Setting::RescanInterval(AddressState::Untested)),
381                                 self.get_u64(U64Setting::RescanInterval(AddressState::LowBlockCount)),
382                                 self.get_u64(U64Setting::RescanInterval(AddressState::HighBlockCount)),
383                                 self.get_u64(U64Setting::RescanInterval(AddressState::LowVersion)),
384                                 self.get_u64(U64Setting::RescanInterval(AddressState::BadVersion)),
385                                 self.get_u64(U64Setting::RescanInterval(AddressState::NotFullNode)),
386                                 self.get_u64(U64Setting::RescanInterval(AddressState::ProtocolViolation)),
387                                 self.get_u64(U64Setting::RescanInterval(AddressState::Timeout)),
388                                 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest)),
389                                 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutAwaitingAddr)),
390                                 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutAwaitingBlock)),
391                                 self.get_u64(U64Setting::RescanInterval(AddressState::Good)),
392                                 self.get_u64(U64Setting::RescanInterval(AddressState::WasGood)),
393                                 self.get_regex(RegexSetting::SubverRegex).as_str());
394                         write_all(f, settings_string).and_then(|(mut f, _)| {
395                                 f.poll_sync_all()
396                         }).and_then(|_| {
397                                 tokio::fs::rename(settings_file.clone() + ".tmp", settings_file)
398                         })
399                 });
400
401                 let nodes_file = self.store.clone() + "/nodes";
402                 let nodes_future = File::create(nodes_file.clone() + ".tmp").and_then(move |f| {
403                         let mut nodes_buff = String::new();
404                         {
405                                 let nodes = self.nodes.read().unwrap();
406                                 nodes_buff.reserve(nodes.nodes_to_state.len() * 20);
407                                 for (ref sockaddr, ref node) in nodes.nodes_to_state.iter() {
408                                         nodes_buff += &sockaddr.to_string();
409                                         nodes_buff += ",";
410                                         nodes_buff += &node.state.to_num().to_string();
411                                         nodes_buff += ",";
412                                         nodes_buff += &node.last_services.to_string();
413                                         nodes_buff += "\n";
414                                 }
415                         }
416                         write_all(f, nodes_buff)
417                 }).and_then(|(mut f, _)| {
418                         f.poll_sync_all()
419                 }).and_then(|_| {
420                         tokio::fs::rename(nodes_file.clone() + ".tmp", nodes_file)
421                 });
422
423                 let dns_file = self.store.clone() + "/nodes.dump";
424                 let dns_future = File::create(dns_file.clone() + ".tmp").and_then(move |f| {
425                         let mut dns_buff = String::new();
426                         {
427                                 let nodes = self.nodes.read().unwrap();
428                                 let mut rng = thread_rng();
429                                 for i in &[1u64, 4, 5, 8, 9, 12, 13, 1024, 1025, 1028, 1029, 1032, 1033, 1036, 1037] {
430                                         let mut v6_set = Vec::new();
431                                         let mut v4_set = Vec::new();
432                                         if i.count_ones() == 1 {
433                                                 for j in 0..64 {
434                                                         if i & (1 << j) != 0 {
435                                                                 let set_ref = &nodes.good_node_services[j];
436                                                                 v4_set = set_ref.iter().filter(|e| e.is_ipv4() && e.port() == 8333)
437                                                                         .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
438                                                                 v6_set = set_ref.iter().filter(|e| e.is_ipv6() && e.port() == 8333)
439                                                                         .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
440                                                                 break;
441                                                         }
442                                                 }
443                                         } else if i.count_ones() == 2 {
444                                                 let mut first_set = None;
445                                                 let mut second_set = None;
446                                                 for j in 0..64 {
447                                                         if i & (1 << j) != 0 {
448                                                                 if first_set == None {
449                                                                         first_set = Some(&nodes.good_node_services[j]);
450                                                                 } else {
451                                                                         second_set = Some(&nodes.good_node_services[j]);
452                                                                         break;
453                                                                 }
454                                                         }
455                                                 }
456                                                 v4_set = first_set.unwrap().intersection(&second_set.unwrap())
457                                                         .filter(|e| e.is_ipv4() && e.port() == 8333)
458                                                         .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
459                                                 v6_set = first_set.unwrap().intersection(&second_set.unwrap())
460                                                         .filter(|e| e.is_ipv6() && e.port() == 8333)
461                                                         .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
462                                         } else {
463                                                 //TODO: Could optimize this one a bit
464                                                 let mut intersection;
465                                                 let mut intersection_set_ref = None;
466                                                 for j in 0..64 {
467                                                         if i & (1 << j) != 0 {
468                                                                 if intersection_set_ref == None {
469                                                                         intersection_set_ref = Some(&nodes.good_node_services[j]);
470                                                                 } else {
471                                                                         let new_intersection = intersection_set_ref.unwrap()
472                                                                                 .intersection(&nodes.good_node_services[j]).map(|e| (*e).clone()).collect();
473                                                                         intersection = Some(new_intersection);
474                                                                         intersection_set_ref = Some(intersection.as_ref().unwrap());
475                                                                 }
476                                                         }
477                                                 }
478                                                 v4_set = intersection_set_ref.unwrap().iter()
479                                                         .filter(|e| e.is_ipv4() && e.port() == 8333)
480                                                         .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
481                                                 v6_set = intersection_set_ref.unwrap().iter()
482                                                         .filter(|e| e.is_ipv6() && e.port() == 8333)
483                                                         .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
484                                         }
485                                         for a in v4_set {
486                                                 dns_buff += &format!("x{:x}.dnsseed\tIN\tA\t{}\n", i, a);
487                                         }
488                                         for a in v6_set {
489                                                 dns_buff += &format!("x{:x}.dnsseed\tIN\tAAAA\t{}\n", i, a);
490                                         }
491                                 }
492                         }
493                         write_all(f, dns_buff)
494                 }).and_then(|(mut f, _)| {
495                         f.poll_sync_all()
496                 }).and_then(|_| {
497                         tokio::fs::rename(dns_file.clone() + ".tmp", dns_file)
498                 });
499
500                 settings_future.join3(nodes_future, dns_future).then(|_| { future::ok(()) })
501         }
502
503         pub fn get_next_scan_nodes(&self) -> Vec<SocketAddr> {
504                 let results = 30 * self.get_u64(U64Setting::ConnsPerSec) as usize;
505                 let per_bucket_results = results / (AddressState::get_count() as usize);
506                 let mut res = Vec::with_capacity(results);
507                 let cur_time = Instant::now();
508
509                 {
510                         let mut nodes = self.nodes.write().unwrap();
511                         for (idx, state_nodes) in nodes.state_next_scan.iter_mut().enumerate() {
512                                 let cmp_time = cur_time - Duration::from_secs(self.get_u64(U64Setting::RescanInterval(AddressState::from_num(idx as u8).unwrap())));
513                                 let split_point = cmp::min(cmp::min(results - res.len(), (per_bucket_results * (idx + 1)) - res.len()),
514                                                 state_nodes.binary_search_by(|a| a.0.cmp(&cmp_time)).unwrap_or_else(|idx| idx));
515                                 let mut new_nodes = state_nodes.split_off(split_point);
516                                 mem::swap(&mut new_nodes, state_nodes);
517                                 for (_, node) in new_nodes.drain(..) {
518                                         res.push(node);
519                                 }
520                         }
521                 }
522                 res.shuffle(&mut thread_rng());
523                 res
524         }
525 }