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