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