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