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 {
34 #[derive(Hash, PartialEq, Eq)]
39 RescanInterval(AddressState),
43 #[derive(Hash, PartialEq, Eq)]
44 pub enum RegexSetting {
50 last_good: Instant, // Ignored unless state is Good or WasGood
56 good_node_services: HashMap<u8, HashSet<SocketAddr>>,
57 nodes_to_state: HashMap<SocketAddr, Node>,
58 state_next_scan: HashMap<AddressState, Vec<(Instant, SocketAddr)>>,
60 struct NodesMutRef<'a> {
61 good_node_services: &'a mut HashMap<u8, HashSet<SocketAddr>>,
62 nodes_to_state: &'a mut HashMap<SocketAddr, Node>,
63 state_next_scan: &'a mut HashMap<AddressState, Vec<(Instant, SocketAddr)>>,
67 fn borrow_mut<'a>(&'a mut self) -> NodesMutRef<'a> {
69 good_node_services: &mut self.good_node_services,
70 nodes_to_state: &mut self.nodes_to_state,
71 state_next_scan: &mut self.state_next_scan,
77 u64_settings: RwLock<HashMap<U64Setting, u64>>,
78 subver_regex: RwLock<Arc<Regex>>,
84 pub fn new(store: String) -> impl Future<Item=Store, Error=()> {
85 let settings_future = File::open(store.clone() + "/settings").and_then(|f| {
86 let mut l = BufReader::new(f).lines();
87 macro_rules! try_read {
88 ($lines: expr, $ty: ty) => { {
90 Some(line) => match line {
91 Ok(line) => match line.parse::<$ty>() {
93 Err(e) => return future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
95 Err(e) => return future::err(e),
97 None => return future::err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "")),
101 let mut u64s = HashMap::with_capacity(15);
102 u64s.insert(U64Setting::ConnsPerSec, try_read!(l, u64));
103 u64s.insert(U64Setting::RunTimeout, try_read!(l, u64));
104 u64s.insert(U64Setting::WasGoodTimeout, try_read!(l, u64));
105 u64s.insert(U64Setting::MinProtocolVersion, try_read!(l, u64));
106 u64s.insert(U64Setting::RescanInterval(AddressState::Untested), try_read!(l, u64));
107 u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), try_read!(l, u64));
108 u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), try_read!(l, u64));
109 u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), try_read!(l, u64));
110 u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), try_read!(l, u64));
111 u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), try_read!(l, u64));
112 u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), try_read!(l, u64));
113 u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), try_read!(l, u64));
114 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), try_read!(l, u64));
115 u64s.insert(U64Setting::RescanInterval(AddressState::Good), try_read!(l, u64));
116 u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), try_read!(l, u64));
117 future::ok((u64s, try_read!(l, Regex)))
118 }).or_else(|_| -> future::FutureResult<(HashMap<U64Setting, u64>, Regex), ()> {
119 let mut u64s = HashMap::with_capacity(15);
120 u64s.insert(U64Setting::ConnsPerSec, 10);
121 u64s.insert(U64Setting::RunTimeout, 120);
122 u64s.insert(U64Setting::WasGoodTimeout, 21600);
123 u64s.insert(U64Setting::RescanInterval(AddressState::Untested), 0);
124 u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), 3600);
125 u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), 7200);
126 u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), 21600);
127 u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), 21600);
128 u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), 86400);
129 u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), 86400);
130 u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), 86400);
131 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), 21600);
132 u64s.insert(U64Setting::RescanInterval(AddressState::Good), 1800);
133 u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), 1800);
134 u64s.insert(U64Setting::MinProtocolVersion, 10000); //XXX
135 future::ok((u64s, Regex::new(".*").unwrap()))
138 macro_rules! nodes_uninitd {
140 let mut state_vecs = HashMap::with_capacity(11);
141 state_vecs.insert(AddressState::Untested, Vec::new());
142 state_vecs.insert(AddressState::LowBlockCount, Vec::new());
143 state_vecs.insert(AddressState::HighBlockCount, Vec::new());
144 state_vecs.insert(AddressState::LowVersion, Vec::new());
145 state_vecs.insert(AddressState::BadVersion, Vec::new());
146 state_vecs.insert(AddressState::NotFullNode, Vec::new());
147 state_vecs.insert(AddressState::ProtocolViolation, Vec::new());
148 state_vecs.insert(AddressState::Timeout, Vec::new());
149 state_vecs.insert(AddressState::TimeoutDuringRequest, Vec::new());
150 state_vecs.insert(AddressState::Good, Vec::new());
151 state_vecs.insert(AddressState::WasGood, Vec::new());
152 let mut good_node_services = HashMap::with_capacity(64);
154 good_node_services.insert(i, HashSet::new());
158 nodes_to_state: HashMap::new(),
159 state_next_scan: state_vecs,
164 let nodes_future = File::open(store.clone() + "/nodes").and_then(|f| {
165 let mut res = nodes_uninitd!();
166 let l = BufReader::new(f).lines();
168 let line = match line_res {
170 Err(_) => return future::ok(res),
172 let mut line_iter = line.split(',');
173 macro_rules! try_read {
174 ($lines: expr, $ty: ty) => { {
175 match $lines.next() {
176 Some(line) => match line.parse::<$ty>() {
178 Err(_) => return future::ok(res),
180 None => return future::ok(res),
184 let sockaddr = try_read!(line_iter, SocketAddr);
185 let state = try_read!(line_iter, u8);
186 let last_services = try_read!(line_iter, u64);
189 0x0 => AddressState::Untested,
190 0x1 => AddressState::LowBlockCount,
191 0x2 => AddressState::HighBlockCount,
192 0x3 => AddressState::LowVersion,
193 0x4 => AddressState::BadVersion,
194 0x5 => AddressState::NotFullNode,
195 0x6 => AddressState::ProtocolViolation,
196 0x7 => AddressState::Timeout,
197 0x8 => AddressState::TimeoutDuringRequest,
198 0x9 => AddressState::Good,
199 0xa => AddressState::WasGood,
200 _ => return future::ok(res),
203 last_update: Instant::now(),
204 last_good: Instant::now(),
206 if node.state == AddressState::Good {
208 if node.last_services & (1 << i) != 0 {
209 res.good_node_services.get_mut(&i).unwrap().insert(sockaddr);
213 res.state_next_scan.get_mut(&node.state).unwrap().push((Instant::now(), sockaddr));
214 res.nodes_to_state.insert(sockaddr, node);
217 }).or_else(|_| -> future::FutureResult<Nodes, ()> {
218 future::ok(nodes_uninitd!())
220 settings_future.join(nodes_future).and_then(move |((u64_settings, regex), nodes)| {
222 u64_settings: RwLock::new(u64_settings),
223 subver_regex: RwLock::new(Arc::new(regex)),
224 nodes: RwLock::new(nodes),
230 pub fn get_u64(&self, setting: U64Setting) -> u64 {
231 *self.u64_settings.read().unwrap().get(&setting).unwrap()
234 pub fn set_u64(&self, setting: U64Setting, value: u64) {
235 *self.u64_settings.write().unwrap().get_mut(&setting).unwrap() = value;
238 pub fn get_node_count(&self, state: AddressState) -> usize {
239 self.nodes.read().unwrap().state_next_scan.get(&state).unwrap().len()
242 pub fn get_regex(&self, _setting: RegexSetting) -> Arc<Regex> {
243 Arc::clone(&*self.subver_regex.read().unwrap())
246 pub fn set_regex(&self, _setting: RegexSetting, value: Regex) {
247 *self.subver_regex.write().unwrap() = Arc::new(value);
250 pub fn add_fresh_nodes(&self, addresses: &Vec<(u32, Address)>) {
251 let mut nodes = self.nodes.write().unwrap();
252 let cur_time = Instant::now();
253 for &(_, ref addr) in addresses {
254 if let Ok(socketaddr) = addr.socket_addr() {
255 match nodes.nodes_to_state.entry(socketaddr.clone()) {
256 hash_map::Entry::Vacant(e) => {
258 state: AddressState::Untested,
260 last_update: cur_time,
261 last_good: Instant::now(),
263 nodes.state_next_scan.get_mut(&AddressState::Untested).unwrap().push((cur_time, socketaddr));
265 hash_map::Entry::Occupied(_) => {},
268 //TODO: Handle onions
273 pub fn set_node_state(&self, addr: SocketAddr, state: AddressState, services: u64) {
274 let mut nodes_lock = self.nodes.write().unwrap();
275 let nodes = nodes_lock.borrow_mut();
276 let state_ref = nodes.nodes_to_state.get_mut(&addr).unwrap();
277 state_ref.last_update = Instant::now();
278 if (state_ref.state == AddressState::Good || state_ref.state == AddressState::WasGood)
279 && state != AddressState::Good
280 && state_ref.last_good >= state_ref.last_update + Duration::from_secs(self.get_u64(U64Setting::WasGoodTimeout)) {
281 state_ref.state = AddressState::WasGood;
283 if state_ref.last_services & (1 << i) != 0 {
284 nodes.good_node_services.get_mut(&i).unwrap().remove(&addr);
287 state_ref.last_services = 0;
288 nodes.state_next_scan.get_mut(&AddressState::WasGood).unwrap().push((state_ref.last_update, addr));
290 state_ref.state = state;
291 if state == AddressState::Good {
293 if services & (1 << i) != 0 && state_ref.last_services & (1 << i) == 0 {
294 nodes.good_node_services.get_mut(&i).unwrap().insert(addr);
295 } else if services & (1 << i) == 0 && state_ref.last_services & (1 << i) != 0 {
296 nodes.good_node_services.get_mut(&i).unwrap().remove(&addr);
299 state_ref.last_services = services;
300 state_ref.last_good = state_ref.last_update;
302 nodes.state_next_scan.get_mut(&state).unwrap().push((state_ref.last_update, addr));
306 pub fn save_data(&'static self) -> impl Future<Item=(), Error=()> {
307 let settings_file = self.store.clone() + "/settings";
308 let settings_future = File::create(settings_file.clone() + ".tmp").and_then(move |f| {
309 let settings_string = format!("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
310 self.get_u64(U64Setting::ConnsPerSec),
311 self.get_u64(U64Setting::RunTimeout),
312 self.get_u64(U64Setting::WasGoodTimeout),
313 self.get_u64(U64Setting::MinProtocolVersion),
314 self.get_u64(U64Setting::RescanInterval(AddressState::Untested)),
315 self.get_u64(U64Setting::RescanInterval(AddressState::LowBlockCount)),
316 self.get_u64(U64Setting::RescanInterval(AddressState::HighBlockCount)),
317 self.get_u64(U64Setting::RescanInterval(AddressState::LowVersion)),
318 self.get_u64(U64Setting::RescanInterval(AddressState::BadVersion)),
319 self.get_u64(U64Setting::RescanInterval(AddressState::NotFullNode)),
320 self.get_u64(U64Setting::RescanInterval(AddressState::ProtocolViolation)),
321 self.get_u64(U64Setting::RescanInterval(AddressState::Timeout)),
322 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest)),
323 self.get_u64(U64Setting::RescanInterval(AddressState::Good)),
324 self.get_u64(U64Setting::RescanInterval(AddressState::WasGood)),
325 self.get_regex(RegexSetting::SubverRegex).as_str());
326 write_all(f, settings_string).and_then(|(mut f, _)| {
329 tokio::fs::rename(settings_file.clone() + ".tmp", settings_file)
333 let nodes_file = self.store.clone() + "/nodes";
334 let nodes_future = File::create(nodes_file.clone() + ".tmp").and_then(move |f| {
335 let mut nodes_buff = String::new();
337 let nodes = self.nodes.read().unwrap();
338 nodes_buff.reserve(nodes.nodes_to_state.len() * 20);
339 for (ref sockaddr, ref node) in nodes.nodes_to_state.iter() {
340 nodes_buff += &sockaddr.to_string();
342 nodes_buff += &match node.state {
343 AddressState::Untested => 0u8,
344 AddressState::LowBlockCount => 1u8,
345 AddressState::HighBlockCount => 2u8,
346 AddressState::LowVersion => 3u8,
347 AddressState::BadVersion => 4u8,
348 AddressState::NotFullNode => 5u8,
349 AddressState::ProtocolViolation => 6u8,
350 AddressState::Timeout => 7u8,
351 AddressState::TimeoutDuringRequest => 8u8,
352 AddressState::Good => 9u8,
353 AddressState::WasGood => 10u8,
356 nodes_buff += &node.last_services.to_string();
360 write_all(f, nodes_buff)
361 }).and_then(|(mut f, _)| {
364 tokio::fs::rename(nodes_file.clone() + ".tmp", nodes_file)
367 let dns_file = self.store.clone() + "/nodes.dump";
368 let dns_future = File::create(dns_file.clone() + ".tmp").and_then(move |f| {
369 let mut dns_buff = String::new();
371 let nodes = self.nodes.read().unwrap();
372 let mut rng = thread_rng();
373 for i in &[1u64, 4, 5, 8, 9, 12, 13, 1024, 1025, 1028, 1029, 1032, 1033, 1036, 1037] {
374 let mut v6_set = Vec::new();
375 let mut v4_set = Vec::new();
376 if i.count_ones() == 1 {
378 if i & (1 << j) != 0 {
379 let set_ref = nodes.good_node_services.get(&j).unwrap();
380 v4_set = set_ref.iter().filter(|e| e.is_ipv4() && e.port() == 8333)
381 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
382 v6_set = set_ref.iter().filter(|e| e.is_ipv6() && e.port() == 8333)
383 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
387 } else if i.count_ones() == 2 {
388 let mut first_set = None;
389 let mut second_set = None;
391 if i & (1 << j) != 0 {
392 if first_set == None {
393 first_set = Some(nodes.good_node_services.get(&j).unwrap());
395 second_set = Some(nodes.good_node_services.get(&j).unwrap());
400 v4_set = first_set.unwrap().intersection(second_set.unwrap())
401 .filter(|e| e.is_ipv4() && e.port() == 8333)
402 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
403 v6_set = first_set.unwrap().intersection(second_set.unwrap())
404 .filter(|e| e.is_ipv6() && e.port() == 8333)
405 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
407 //TODO: Could optimize this one a bit
408 let mut intersection;
409 let mut intersection_set_ref = None;
411 if i & (1 << j) != 0 {
412 if intersection_set_ref == None {
413 intersection_set_ref = Some(nodes.good_node_services.get(&j).unwrap());
415 let new_intersection = intersection_set_ref.unwrap()
416 .intersection(nodes.good_node_services.get(&j).unwrap()).map(|e| (*e).clone()).collect();
417 intersection = Some(new_intersection);
418 intersection_set_ref = Some(intersection.as_ref().unwrap());
422 v4_set = intersection_set_ref.unwrap().iter()
423 .filter(|e| e.is_ipv4() && e.port() == 8333)
424 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
425 v6_set = intersection_set_ref.unwrap().iter()
426 .filter(|e| e.is_ipv6() && e.port() == 8333)
427 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
430 dns_buff += &format!("x{:x}.dnsseed\tIN\tA\t{}\n", i, a);
433 dns_buff += &format!("x{:x}.dnsseed\tIN\tAAAA\t{}\n", i, a);
437 write_all(f, dns_buff)
438 }).and_then(|(mut f, _)| {
441 tokio::fs::rename(dns_file.clone() + ".tmp", dns_file)
444 settings_future.join3(nodes_future, dns_future).then(|_| { future::ok(()) })
447 pub fn get_next_scan_nodes(&self) -> Vec<SocketAddr> {
448 let mut res = Vec::with_capacity(600);
449 let cur_time = Instant::now();
450 let mut nodes = self.nodes.write().unwrap();
451 for (state, state_nodes) in nodes.state_next_scan.iter_mut() {
452 let cmp_time = cur_time - Duration::from_secs(self.get_u64(U64Setting::RescanInterval(*state)));
453 let split_point = cmp::min(cmp::min(600 - res.len(), 60),
454 state_nodes.binary_search_by(|a| a.0.cmp(&cmp_time)).unwrap_or_else(|idx| idx));
455 let mut new_nodes = state_nodes.split_off(split_point);
456 mem::swap(&mut new_nodes, state_nodes);
457 for (_, node) in new_nodes.drain(..) {
461 res.shuffle(&mut thread_rng());