2 use std::collections::{HashSet, HashMap, hash_map};
3 use std::sync::{Arc, RwLock};
4 use std::net::SocketAddr;
5 use std::time::{Duration, Instant};
6 use std::io::{BufRead, BufReader};
8 use bitcoin::network::address::Address;
11 use rand::seq::{SliceRandom, IteratorRandom};
13 use tokio::prelude::*;
15 use tokio::io::write_all;
19 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
20 pub enum AddressState {
35 pub fn from_num(num: u8) -> Option<AddressState> {
37 0x0 => Some(AddressState::Untested),
38 0x1 => Some(AddressState::LowBlockCount),
39 0x2 => Some(AddressState::HighBlockCount),
40 0x3 => Some(AddressState::LowVersion),
41 0x4 => Some(AddressState::BadVersion),
42 0x5 => Some(AddressState::NotFullNode),
43 0x6 => Some(AddressState::ProtocolViolation),
44 0x7 => Some(AddressState::Timeout),
45 0x8 => Some(AddressState::TimeoutDuringRequest),
46 0x9 => Some(AddressState::Good),
47 0xa => Some(AddressState::WasGood),
52 pub fn to_num(&self) -> u8 {
54 AddressState::Untested => 0,
55 AddressState::LowBlockCount => 1,
56 AddressState::HighBlockCount => 2,
57 AddressState::LowVersion => 3,
58 AddressState::BadVersion => 4,
59 AddressState::NotFullNode => 5,
60 AddressState::ProtocolViolation => 6,
61 AddressState::Timeout => 7,
62 AddressState::TimeoutDuringRequest => 8,
63 AddressState::Good => 9,
64 AddressState::WasGood => 10,
68 pub fn to_str(&self) -> &'static str {
70 AddressState::Untested => "Untested",
71 AddressState::LowBlockCount => "Low Block Count",
72 AddressState::HighBlockCount => "High Block Count",
73 AddressState::LowVersion => "Low Version",
74 AddressState::BadVersion => "Bad Version",
75 AddressState::NotFullNode => "Not Full Node",
76 AddressState::ProtocolViolation => "Protocol Violation",
77 AddressState::Timeout => "Timeout",
78 AddressState::TimeoutDuringRequest => "Timeout During Request",
79 AddressState::Good => "Good",
80 AddressState::WasGood => "Was Good",
84 pub fn get_count() -> u8 {
89 #[derive(Hash, PartialEq, Eq)]
94 RescanInterval(AddressState),
98 #[derive(Hash, PartialEq, Eq)]
99 pub enum RegexSetting {
104 last_update: Instant,
105 last_good: Instant, // Ignored unless state is Good or WasGood
111 good_node_services: HashMap<u8, HashSet<SocketAddr>>,
112 nodes_to_state: HashMap<SocketAddr, Node>,
113 state_next_scan: Vec<Vec<(Instant, SocketAddr)>>,
115 struct NodesMutRef<'a> {
116 good_node_services: &'a mut HashMap<u8, HashSet<SocketAddr>>,
117 nodes_to_state: &'a mut HashMap<SocketAddr, Node>,
118 state_next_scan: &'a mut Vec<Vec<(Instant, SocketAddr)>>,
122 fn borrow_mut<'a>(&'a mut self) -> NodesMutRef<'a> {
124 good_node_services: &mut self.good_node_services,
125 nodes_to_state: &mut self.nodes_to_state,
126 state_next_scan: &mut self.state_next_scan,
132 u64_settings: RwLock<HashMap<U64Setting, u64>>,
133 subver_regex: RwLock<Arc<Regex>>,
134 nodes: RwLock<Nodes>,
139 pub fn new(store: String) -> impl Future<Item=Store, Error=()> {
140 let settings_future = File::open(store.clone() + "/settings").and_then(|f| {
141 let mut l = BufReader::new(f).lines();
142 macro_rules! try_read {
143 ($lines: expr, $ty: ty) => { {
144 match $lines.next() {
145 Some(line) => match line {
146 Ok(line) => match line.parse::<$ty>() {
148 Err(e) => return future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
150 Err(e) => return future::err(e),
152 None => return future::err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "")),
156 let mut u64s = HashMap::with_capacity(15);
157 u64s.insert(U64Setting::ConnsPerSec, try_read!(l, u64));
158 u64s.insert(U64Setting::RunTimeout, try_read!(l, u64));
159 u64s.insert(U64Setting::WasGoodTimeout, try_read!(l, u64));
160 u64s.insert(U64Setting::MinProtocolVersion, try_read!(l, u64));
161 u64s.insert(U64Setting::RescanInterval(AddressState::Untested), try_read!(l, u64));
162 u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), try_read!(l, u64));
163 u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), try_read!(l, u64));
164 u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), try_read!(l, u64));
165 u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), try_read!(l, u64));
166 u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), try_read!(l, u64));
167 u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), try_read!(l, u64));
168 u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), try_read!(l, u64));
169 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), try_read!(l, u64));
170 u64s.insert(U64Setting::RescanInterval(AddressState::Good), try_read!(l, u64));
171 u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), try_read!(l, u64));
172 future::ok((u64s, try_read!(l, Regex)))
173 }).or_else(|_| -> future::FutureResult<(HashMap<U64Setting, u64>, Regex), ()> {
174 let mut u64s = HashMap::with_capacity(15);
175 u64s.insert(U64Setting::ConnsPerSec, 10);
176 u64s.insert(U64Setting::RunTimeout, 120);
177 u64s.insert(U64Setting::WasGoodTimeout, 21600);
178 u64s.insert(U64Setting::RescanInterval(AddressState::Untested), 0);
179 u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), 3600);
180 u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), 7200);
181 u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), 21600);
182 u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), 21600);
183 u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), 86400);
184 u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), 86400);
185 u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), 86400);
186 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), 21600);
187 u64s.insert(U64Setting::RescanInterval(AddressState::Good), 1800);
188 u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), 1800);
189 u64s.insert(U64Setting::MinProtocolVersion, 10000); //XXX
190 future::ok((u64s, Regex::new(".*").unwrap()))
193 macro_rules! nodes_uninitd {
195 let mut state_vecs = Vec::with_capacity(AddressState::get_count() as usize);
196 for _ in 0..AddressState::get_count() {
197 state_vecs.push(Vec::new());
199 let mut good_node_services = HashMap::with_capacity(64);
201 good_node_services.insert(i, HashSet::new());
205 nodes_to_state: HashMap::new(),
206 state_next_scan: state_vecs,
211 let nodes_future = File::open(store.clone() + "/nodes").and_then(|f| {
212 let mut res = nodes_uninitd!();
213 let l = BufReader::new(f).lines();
215 let line = match line_res {
217 Err(_) => return future::ok(res),
219 let mut line_iter = line.split(',');
220 macro_rules! try_read {
221 ($lines: expr, $ty: ty) => { {
222 match $lines.next() {
223 Some(line) => match line.parse::<$ty>() {
225 Err(_) => return future::ok(res),
227 None => return future::ok(res),
231 let sockaddr = try_read!(line_iter, SocketAddr);
232 let state = try_read!(line_iter, u8);
233 let last_services = try_read!(line_iter, u64);
235 state: match AddressState::from_num(state) {
237 None => return future::ok(res),
240 last_update: Instant::now(),
241 last_good: Instant::now(),
243 if node.state == AddressState::Good {
245 if node.last_services & (1 << i) != 0 {
246 res.good_node_services.get_mut(&i).unwrap().insert(sockaddr);
250 res.state_next_scan[node.state.to_num() as usize].push((Instant::now(), sockaddr));
251 res.nodes_to_state.insert(sockaddr, node);
254 }).or_else(|_| -> future::FutureResult<Nodes, ()> {
255 future::ok(nodes_uninitd!())
257 settings_future.join(nodes_future).and_then(move |((u64_settings, regex), nodes)| {
259 u64_settings: RwLock::new(u64_settings),
260 subver_regex: RwLock::new(Arc::new(regex)),
261 nodes: RwLock::new(nodes),
267 pub fn get_u64(&self, setting: U64Setting) -> u64 {
268 *self.u64_settings.read().unwrap().get(&setting).unwrap()
271 pub fn set_u64(&self, setting: U64Setting, value: u64) {
272 *self.u64_settings.write().unwrap().get_mut(&setting).unwrap() = value;
275 pub fn get_node_count(&self, state: AddressState) -> usize {
276 self.nodes.read().unwrap().state_next_scan[state.to_num() as usize].len()
279 pub fn get_regex(&self, _setting: RegexSetting) -> Arc<Regex> {
280 Arc::clone(&*self.subver_regex.read().unwrap())
283 pub fn set_regex(&self, _setting: RegexSetting, value: Regex) {
284 *self.subver_regex.write().unwrap() = Arc::new(value);
287 pub fn add_fresh_addrs<I: Iterator<Item=SocketAddr>>(&self, addresses: I) -> u64 {
289 let mut nodes = self.nodes.write().unwrap();
290 let cur_time = Instant::now();
291 for addr in addresses {
292 match nodes.nodes_to_state.entry(addr.clone()) {
293 hash_map::Entry::Vacant(e) => {
295 state: AddressState::Untested,
297 last_update: cur_time,
300 nodes.state_next_scan[AddressState::Untested.to_num() as usize].push((cur_time, addr));
303 hash_map::Entry::Occupied(_) => {},
309 pub fn add_fresh_nodes(&self, addresses: &Vec<(u32, Address)>) {
310 self.add_fresh_addrs(addresses.iter().filter_map(|(_, addr)| {
311 match addr.socket_addr() {
312 Ok(socketaddr) => Some(socketaddr),
313 Err(_) => None, // TODO: Handle onions
318 pub fn set_node_state(&self, addr: SocketAddr, state: AddressState, services: u64) -> AddressState {
319 let mut nodes_lock = self.nodes.write().unwrap();
320 let nodes = nodes_lock.borrow_mut();
321 let now = Instant::now();
323 let state_ref = nodes.nodes_to_state.entry(addr).or_insert(Node {
324 state: AddressState::Untested,
329 let ret = state_ref.state;
330 if (state_ref.state == AddressState::Good || state_ref.state == AddressState::WasGood)
331 && state != AddressState::Good
332 && state_ref.last_good >= now - Duration::from_secs(self.get_u64(U64Setting::WasGoodTimeout)) {
333 state_ref.state = AddressState::WasGood;
335 if state_ref.last_services & (1 << i) != 0 {
336 nodes.good_node_services.get_mut(&i).unwrap().remove(&addr);
339 state_ref.last_services = 0;
340 nodes.state_next_scan[AddressState::WasGood.to_num() as usize].push((now, addr));
342 state_ref.state = state;
343 if state == AddressState::Good {
345 if services & (1 << i) != 0 && state_ref.last_services & (1 << i) == 0 {
346 nodes.good_node_services.get_mut(&i).unwrap().insert(addr);
347 } else if services & (1 << i) == 0 && state_ref.last_services & (1 << i) != 0 {
348 nodes.good_node_services.get_mut(&i).unwrap().remove(&addr);
351 state_ref.last_services = services;
352 state_ref.last_good = now;
354 nodes.state_next_scan[state.to_num() as usize].push((now, addr));
356 state_ref.last_update = now;
360 pub fn save_data(&'static self) -> impl Future<Item=(), Error=()> {
361 let settings_file = self.store.clone() + "/settings";
362 let settings_future = File::create(settings_file.clone() + ".tmp").and_then(move |f| {
363 let settings_string = format!("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
364 self.get_u64(U64Setting::ConnsPerSec),
365 self.get_u64(U64Setting::RunTimeout),
366 self.get_u64(U64Setting::WasGoodTimeout),
367 self.get_u64(U64Setting::MinProtocolVersion),
368 self.get_u64(U64Setting::RescanInterval(AddressState::Untested)),
369 self.get_u64(U64Setting::RescanInterval(AddressState::LowBlockCount)),
370 self.get_u64(U64Setting::RescanInterval(AddressState::HighBlockCount)),
371 self.get_u64(U64Setting::RescanInterval(AddressState::LowVersion)),
372 self.get_u64(U64Setting::RescanInterval(AddressState::BadVersion)),
373 self.get_u64(U64Setting::RescanInterval(AddressState::NotFullNode)),
374 self.get_u64(U64Setting::RescanInterval(AddressState::ProtocolViolation)),
375 self.get_u64(U64Setting::RescanInterval(AddressState::Timeout)),
376 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest)),
377 self.get_u64(U64Setting::RescanInterval(AddressState::Good)),
378 self.get_u64(U64Setting::RescanInterval(AddressState::WasGood)),
379 self.get_regex(RegexSetting::SubverRegex).as_str());
380 write_all(f, settings_string).and_then(|(mut f, _)| {
383 tokio::fs::rename(settings_file.clone() + ".tmp", settings_file)
387 let nodes_file = self.store.clone() + "/nodes";
388 let nodes_future = File::create(nodes_file.clone() + ".tmp").and_then(move |f| {
389 let mut nodes_buff = String::new();
391 let nodes = self.nodes.read().unwrap();
392 nodes_buff.reserve(nodes.nodes_to_state.len() * 20);
393 for (ref sockaddr, ref node) in nodes.nodes_to_state.iter() {
394 nodes_buff += &sockaddr.to_string();
396 nodes_buff += &node.state.to_num().to_string();
398 nodes_buff += &node.last_services.to_string();
402 write_all(f, nodes_buff)
403 }).and_then(|(mut f, _)| {
406 tokio::fs::rename(nodes_file.clone() + ".tmp", nodes_file)
409 let dns_file = self.store.clone() + "/nodes.dump";
410 let dns_future = File::create(dns_file.clone() + ".tmp").and_then(move |f| {
411 let mut dns_buff = String::new();
413 let nodes = self.nodes.read().unwrap();
414 let mut rng = thread_rng();
415 for i in &[1u64, 4, 5, 8, 9, 12, 13, 1024, 1025, 1028, 1029, 1032, 1033, 1036, 1037] {
416 let mut v6_set = Vec::new();
417 let mut v4_set = Vec::new();
418 if i.count_ones() == 1 {
420 if i & (1 << j) != 0 {
421 let set_ref = nodes.good_node_services.get(&j).unwrap();
422 v4_set = set_ref.iter().filter(|e| e.is_ipv4() && e.port() == 8333)
423 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
424 v6_set = set_ref.iter().filter(|e| e.is_ipv6() && e.port() == 8333)
425 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
429 } else if i.count_ones() == 2 {
430 let mut first_set = None;
431 let mut second_set = None;
433 if i & (1 << j) != 0 {
434 if first_set == None {
435 first_set = Some(nodes.good_node_services.get(&j).unwrap());
437 second_set = Some(nodes.good_node_services.get(&j).unwrap());
442 v4_set = first_set.unwrap().intersection(second_set.unwrap())
443 .filter(|e| e.is_ipv4() && e.port() == 8333)
444 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
445 v6_set = first_set.unwrap().intersection(second_set.unwrap())
446 .filter(|e| e.is_ipv6() && e.port() == 8333)
447 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
449 //TODO: Could optimize this one a bit
450 let mut intersection;
451 let mut intersection_set_ref = None;
453 if i & (1 << j) != 0 {
454 if intersection_set_ref == None {
455 intersection_set_ref = Some(nodes.good_node_services.get(&j).unwrap());
457 let new_intersection = intersection_set_ref.unwrap()
458 .intersection(nodes.good_node_services.get(&j).unwrap()).map(|e| (*e).clone()).collect();
459 intersection = Some(new_intersection);
460 intersection_set_ref = Some(intersection.as_ref().unwrap());
464 v4_set = intersection_set_ref.unwrap().iter()
465 .filter(|e| e.is_ipv4() && e.port() == 8333)
466 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
467 v6_set = intersection_set_ref.unwrap().iter()
468 .filter(|e| e.is_ipv6() && e.port() == 8333)
469 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
472 dns_buff += &format!("x{:x}.dnsseed\tIN\tA\t{}\n", i, a);
475 dns_buff += &format!("x{:x}.dnsseed\tIN\tAAAA\t{}\n", i, a);
479 write_all(f, dns_buff)
480 }).and_then(|(mut f, _)| {
483 tokio::fs::rename(dns_file.clone() + ".tmp", dns_file)
486 settings_future.join3(nodes_future, dns_future).then(|_| { future::ok(()) })
489 pub fn get_next_scan_nodes(&self) -> Vec<SocketAddr> {
490 let results = 30 * self.get_u64(U64Setting::ConnsPerSec) as usize;
491 let per_bucket_results = results / (AddressState::get_count() as usize);
492 let mut res = Vec::with_capacity(results);
493 let cur_time = Instant::now();
496 let mut nodes = self.nodes.write().unwrap();
497 for (idx, state_nodes) in nodes.state_next_scan.iter_mut().enumerate() {
498 let cmp_time = cur_time - Duration::from_secs(self.get_u64(U64Setting::RescanInterval(AddressState::from_num(idx as u8).unwrap())));
499 let split_point = cmp::min(cmp::min(results - res.len(), results - (per_bucket_results * (AddressState::get_count() as usize - idx))),
500 state_nodes.binary_search_by(|a| a.0.cmp(&cmp_time)).unwrap_or_else(|idx| idx));
501 let mut new_nodes = state_nodes.split_off(split_point);
502 mem::swap(&mut new_nodes, state_nodes);
503 for (_, node) in new_nodes.drain(..) {
508 res.shuffle(&mut thread_rng());