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