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 {
38 pub fn from_num(num: u8) -> Option<AddressState> {
40 0x0 => Some(AddressState::Untested),
41 0x1 => Some(AddressState::LowBlockCount),
42 0x2 => Some(AddressState::HighBlockCount),
43 0x3 => Some(AddressState::LowVersion),
44 0x4 => Some(AddressState::BadVersion),
45 0x5 => Some(AddressState::NotFullNode),
46 0x6 => Some(AddressState::ProtocolViolation),
47 0x7 => Some(AddressState::Timeout),
48 0x8 => Some(AddressState::TimeoutDuringRequest),
49 0x9 => Some(AddressState::TimeoutAwaitingPong),
50 0xa => Some(AddressState::TimeoutAwaitingAddr),
51 0xb => Some(AddressState::TimeoutAwaitingBlock),
52 0xc => Some(AddressState::Good),
53 0xd => Some(AddressState::WasGood),
58 pub fn to_num(&self) -> u8 {
60 AddressState::Untested => 0,
61 AddressState::LowBlockCount => 1,
62 AddressState::HighBlockCount => 2,
63 AddressState::LowVersion => 3,
64 AddressState::BadVersion => 4,
65 AddressState::NotFullNode => 5,
66 AddressState::ProtocolViolation => 6,
67 AddressState::Timeout => 7,
68 AddressState::TimeoutDuringRequest => 8,
69 AddressState::TimeoutAwaitingPong => 9,
70 AddressState::TimeoutAwaitingAddr => 10,
71 AddressState::TimeoutAwaitingBlock => 11,
72 AddressState::Good => 12,
73 AddressState::WasGood => 13,
77 pub fn to_str(&self) -> &'static str {
79 AddressState::Untested => "Untested",
80 AddressState::LowBlockCount => "Low Block Count",
81 AddressState::HighBlockCount => "High Block Count",
82 AddressState::LowVersion => "Low Version",
83 AddressState::BadVersion => "Bad Version",
84 AddressState::NotFullNode => "Not Full Node",
85 AddressState::ProtocolViolation => "Protocol Violation",
86 AddressState::Timeout => "Timeout",
87 AddressState::TimeoutDuringRequest => "Timeout During Request",
88 AddressState::TimeoutAwaitingPong => "Timeout Awaiting Pong",
89 AddressState::TimeoutAwaitingAddr => "Timeout Awaiting Addr",
90 AddressState::TimeoutAwaitingBlock => "Timeout Awaiting Block",
91 AddressState::Good => "Good",
92 AddressState::WasGood => "Was Good",
96 pub const fn get_count() -> u8 {
101 #[derive(Hash, PartialEq, Eq)]
102 pub enum U64Setting {
106 RescanInterval(AddressState),
110 #[derive(Hash, PartialEq, Eq)]
111 pub enum RegexSetting {
116 last_update: Instant,
117 last_good: Instant, // Ignored unless state is Good or WasGood
123 good_node_services: Vec<HashSet<SocketAddr>>,
124 nodes_to_state: HashMap<SocketAddr, Node>,
125 state_next_scan: Vec<Vec<(Instant, SocketAddr)>>,
127 struct NodesMutRef<'a> {
128 good_node_services: &'a mut Vec<HashSet<SocketAddr>>,
129 nodes_to_state: &'a mut HashMap<SocketAddr, Node>,
130 state_next_scan: &'a mut Vec<Vec<(Instant, SocketAddr)>>,
134 fn borrow_mut<'a>(&'a mut self) -> NodesMutRef<'a> {
136 good_node_services: &mut self.good_node_services,
137 nodes_to_state: &mut self.nodes_to_state,
138 state_next_scan: &mut self.state_next_scan,
144 u64_settings: RwLock<HashMap<U64Setting, u64>>,
145 subver_regex: RwLock<Arc<Regex>>,
146 nodes: RwLock<Nodes>,
151 pub fn new(store: String) -> impl Future<Item=Store, Error=()> {
152 let settings_future = File::open(store.clone() + "/settings").and_then(|f| {
153 let mut l = BufReader::new(f).lines();
154 macro_rules! try_read {
155 ($lines: expr, $ty: ty) => { {
156 match $lines.next() {
157 Some(line) => match line {
158 Ok(line) => match line.parse::<$ty>() {
160 Err(e) => return future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
162 Err(e) => return future::err(e),
164 None => return future::err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "")),
168 let mut u64s = HashMap::with_capacity(AddressState::get_count() as usize + 4);
169 u64s.insert(U64Setting::ConnsPerSec, try_read!(l, u64));
170 u64s.insert(U64Setting::RunTimeout, try_read!(l, u64));
171 u64s.insert(U64Setting::WasGoodTimeout, try_read!(l, u64));
172 u64s.insert(U64Setting::MinProtocolVersion, try_read!(l, u64));
173 u64s.insert(U64Setting::RescanInterval(AddressState::Untested), try_read!(l, u64));
174 u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), try_read!(l, u64));
175 u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), try_read!(l, u64));
176 u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), try_read!(l, u64));
177 u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), try_read!(l, u64));
178 u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), try_read!(l, u64));
179 u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), try_read!(l, u64));
180 u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), try_read!(l, u64));
181 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), try_read!(l, u64));
182 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingPong), try_read!(l, u64));
183 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingAddr), try_read!(l, u64));
184 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingBlock), try_read!(l, u64));
185 u64s.insert(U64Setting::RescanInterval(AddressState::Good), try_read!(l, u64));
186 u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), try_read!(l, u64));
187 future::ok((u64s, try_read!(l, Regex)))
188 }).or_else(|_| -> future::FutureResult<(HashMap<U64Setting, u64>, Regex), ()> {
189 let mut u64s = HashMap::with_capacity(15);
190 u64s.insert(U64Setting::ConnsPerSec, 10);
191 u64s.insert(U64Setting::RunTimeout, 120);
192 u64s.insert(U64Setting::WasGoodTimeout, 21600);
193 u64s.insert(U64Setting::RescanInterval(AddressState::Untested), 0);
194 u64s.insert(U64Setting::RescanInterval(AddressState::LowBlockCount), 3600);
195 u64s.insert(U64Setting::RescanInterval(AddressState::HighBlockCount), 7200);
196 u64s.insert(U64Setting::RescanInterval(AddressState::LowVersion), 21600);
197 u64s.insert(U64Setting::RescanInterval(AddressState::BadVersion), 21600);
198 u64s.insert(U64Setting::RescanInterval(AddressState::NotFullNode), 86400);
199 u64s.insert(U64Setting::RescanInterval(AddressState::ProtocolViolation), 86400);
200 u64s.insert(U64Setting::RescanInterval(AddressState::Timeout), 86400);
201 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest), 21600);
202 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingPong), 3600);
203 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingAddr), 1800);
204 u64s.insert(U64Setting::RescanInterval(AddressState::TimeoutAwaitingBlock), 3600);
205 u64s.insert(U64Setting::RescanInterval(AddressState::Good), 1800);
206 u64s.insert(U64Setting::RescanInterval(AddressState::WasGood), 1800);
207 u64s.insert(U64Setting::MinProtocolVersion, 70002);
208 future::ok((u64s, Regex::new(".*").unwrap()))
211 macro_rules! nodes_uninitd {
213 let mut state_vecs = Vec::with_capacity(AddressState::get_count() as usize);
214 for _ in 0..AddressState::get_count() {
215 state_vecs.push(Vec::new());
217 let mut good_node_services = Vec::with_capacity(64);
219 good_node_services.push(HashSet::new());
223 nodes_to_state: HashMap::new(),
224 state_next_scan: state_vecs,
229 let nodes_future = File::open(store.clone() + "/nodes").and_then(|f| {
230 let mut res = nodes_uninitd!();
231 let l = BufReader::new(f).lines();
233 let line = match line_res {
235 Err(_) => return future::ok(res),
237 let mut line_iter = line.split(',');
238 macro_rules! try_read {
239 ($lines: expr, $ty: ty) => { {
240 match $lines.next() {
241 Some(line) => match line.parse::<$ty>() {
243 Err(_) => return future::ok(res),
245 None => return future::ok(res),
249 let sockaddr = try_read!(line_iter, SocketAddr);
250 let state = try_read!(line_iter, u8);
251 let last_services = try_read!(line_iter, u64);
253 state: match AddressState::from_num(state) {
255 None => return future::ok(res),
258 last_update: Instant::now(),
259 last_good: Instant::now(),
261 if node.state == AddressState::Good {
263 if node.last_services & (1 << i) != 0 {
264 res.good_node_services[i].insert(sockaddr);
268 res.state_next_scan[node.state.to_num() as usize].push((Instant::now(), sockaddr));
269 res.nodes_to_state.insert(sockaddr, node);
272 }).or_else(|_| -> future::FutureResult<Nodes, ()> {
273 future::ok(nodes_uninitd!())
275 settings_future.join(nodes_future).and_then(move |((u64_settings, regex), nodes)| {
277 u64_settings: RwLock::new(u64_settings),
278 subver_regex: RwLock::new(Arc::new(regex)),
279 nodes: RwLock::new(nodes),
285 pub fn get_u64(&self, setting: U64Setting) -> u64 {
286 *self.u64_settings.read().unwrap().get(&setting).unwrap()
289 pub fn set_u64(&self, setting: U64Setting, value: u64) {
290 *self.u64_settings.write().unwrap().get_mut(&setting).unwrap() = value;
293 pub fn get_node_count(&self, state: AddressState) -> usize {
294 self.nodes.read().unwrap().state_next_scan[state.to_num() as usize].len()
297 pub fn get_regex(&self, _setting: RegexSetting) -> Arc<Regex> {
298 Arc::clone(&*self.subver_regex.read().unwrap())
301 pub fn set_regex(&self, _setting: RegexSetting, value: Regex) {
302 *self.subver_regex.write().unwrap() = Arc::new(value);
305 pub fn add_fresh_addrs<I: Iterator<Item=SocketAddr>>(&self, addresses: I) -> u64 {
307 let mut nodes = self.nodes.write().unwrap();
308 let cur_time = Instant::now();
309 for addr in addresses {
310 match nodes.nodes_to_state.entry(addr.clone()) {
311 hash_map::Entry::Vacant(e) => {
313 state: AddressState::Untested,
315 last_update: cur_time,
318 nodes.state_next_scan[AddressState::Untested.to_num() as usize].push((cur_time, addr));
321 hash_map::Entry::Occupied(_) => {},
327 pub fn add_fresh_nodes(&self, addresses: &Vec<(u32, Address)>) {
328 self.add_fresh_addrs(addresses.iter().filter_map(|(_, addr)| {
329 match addr.socket_addr() {
330 Ok(socketaddr) => Some(socketaddr),
331 Err(_) => None, // TODO: Handle onions
336 pub fn set_node_state(&self, addr: SocketAddr, state: AddressState, services: u64) -> AddressState {
337 let mut nodes_lock = self.nodes.write().unwrap();
338 let nodes = nodes_lock.borrow_mut();
339 let now = Instant::now();
341 let state_ref = nodes.nodes_to_state.entry(addr).or_insert(Node {
342 state: AddressState::Untested,
347 let ret = state_ref.state;
348 if (state_ref.state == AddressState::Good || state_ref.state == AddressState::WasGood)
349 && state != AddressState::Good
350 && state_ref.last_good >= now - Duration::from_secs(self.get_u64(U64Setting::WasGoodTimeout)) {
351 state_ref.state = AddressState::WasGood;
353 if state_ref.last_services & (1 << i) != 0 {
354 nodes.good_node_services[i].remove(&addr);
357 state_ref.last_services = 0;
358 nodes.state_next_scan[AddressState::WasGood.to_num() as usize].push((now, addr));
360 state_ref.state = state;
361 if state == AddressState::Good {
363 if services & (1 << i) != 0 && state_ref.last_services & (1 << i) == 0 {
364 nodes.good_node_services[i].insert(addr);
365 } else if services & (1 << i) == 0 && state_ref.last_services & (1 << i) != 0 {
366 nodes.good_node_services[i].remove(&addr);
369 state_ref.last_services = services;
370 state_ref.last_good = now;
372 nodes.state_next_scan[state.to_num() as usize].push((now, addr));
374 state_ref.last_update = now;
378 pub fn save_data(&'static self) -> impl Future<Item=(), Error=()> {
379 let settings_file = self.store.clone() + "/settings";
380 let settings_future = File::create(settings_file.clone() + ".tmp").and_then(move |f| {
381 let settings_string = format!("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
382 self.get_u64(U64Setting::ConnsPerSec),
383 self.get_u64(U64Setting::RunTimeout),
384 self.get_u64(U64Setting::WasGoodTimeout),
385 self.get_u64(U64Setting::MinProtocolVersion),
386 self.get_u64(U64Setting::RescanInterval(AddressState::Untested)),
387 self.get_u64(U64Setting::RescanInterval(AddressState::LowBlockCount)),
388 self.get_u64(U64Setting::RescanInterval(AddressState::HighBlockCount)),
389 self.get_u64(U64Setting::RescanInterval(AddressState::LowVersion)),
390 self.get_u64(U64Setting::RescanInterval(AddressState::BadVersion)),
391 self.get_u64(U64Setting::RescanInterval(AddressState::NotFullNode)),
392 self.get_u64(U64Setting::RescanInterval(AddressState::ProtocolViolation)),
393 self.get_u64(U64Setting::RescanInterval(AddressState::Timeout)),
394 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutDuringRequest)),
395 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutAwaitingPong)),
396 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutAwaitingAddr)),
397 self.get_u64(U64Setting::RescanInterval(AddressState::TimeoutAwaitingBlock)),
398 self.get_u64(U64Setting::RescanInterval(AddressState::Good)),
399 self.get_u64(U64Setting::RescanInterval(AddressState::WasGood)),
400 self.get_regex(RegexSetting::SubverRegex).as_str());
401 write_all(f, settings_string).and_then(|(mut f, _)| {
404 tokio::fs::rename(settings_file.clone() + ".tmp", settings_file)
408 let nodes_file = self.store.clone() + "/nodes";
409 let nodes_future = File::create(nodes_file.clone() + ".tmp").and_then(move |f| {
410 let mut nodes_buff = String::new();
412 let nodes = self.nodes.read().unwrap();
413 nodes_buff.reserve(nodes.nodes_to_state.len() * 20);
414 for (ref sockaddr, ref node) in nodes.nodes_to_state.iter() {
415 nodes_buff += &sockaddr.to_string();
417 nodes_buff += &node.state.to_num().to_string();
419 nodes_buff += &node.last_services.to_string();
423 write_all(f, nodes_buff)
424 }).and_then(|(mut f, _)| {
427 tokio::fs::rename(nodes_file.clone() + ".tmp", nodes_file)
430 let dns_file = self.store.clone() + "/nodes.dump";
431 let dns_future = File::create(dns_file.clone() + ".tmp").and_then(move |f| {
432 let mut dns_buff = String::new();
434 let nodes = self.nodes.read().unwrap();
435 let mut rng = thread_rng();
436 for i in &[1u64, 4, 5, 8, 9, 12, 13, 1024, 1025, 1028, 1029, 1032, 1033, 1036, 1037] {
437 let mut v6_set = Vec::new();
438 let mut v4_set = Vec::new();
439 if i.count_ones() == 1 {
441 if i & (1 << j) != 0 {
442 let set_ref = &nodes.good_node_services[j];
443 v4_set = set_ref.iter().filter(|e| e.is_ipv4() && e.port() == 8333)
444 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
445 v6_set = set_ref.iter().filter(|e| e.is_ipv6() && e.port() == 8333)
446 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
450 } else if i.count_ones() == 2 {
451 let mut first_set = None;
452 let mut second_set = None;
454 if i & (1 << j) != 0 {
455 if first_set == None {
456 first_set = Some(&nodes.good_node_services[j]);
458 second_set = Some(&nodes.good_node_services[j]);
463 v4_set = first_set.unwrap().intersection(&second_set.unwrap())
464 .filter(|e| e.is_ipv4() && e.port() == 8333)
465 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
466 v6_set = first_set.unwrap().intersection(&second_set.unwrap())
467 .filter(|e| e.is_ipv6() && e.port() == 8333)
468 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
470 //TODO: Could optimize this one a bit
471 let mut intersection;
472 let mut intersection_set_ref = None;
474 if i & (1 << j) != 0 {
475 if intersection_set_ref == None {
476 intersection_set_ref = Some(&nodes.good_node_services[j]);
478 let new_intersection = intersection_set_ref.unwrap()
479 .intersection(&nodes.good_node_services[j]).map(|e| (*e).clone()).collect();
480 intersection = Some(new_intersection);
481 intersection_set_ref = Some(intersection.as_ref().unwrap());
485 v4_set = intersection_set_ref.unwrap().iter()
486 .filter(|e| e.is_ipv4() && e.port() == 8333)
487 .choose_multiple(&mut rng, 21).iter().map(|e| e.ip()).collect();
488 v6_set = intersection_set_ref.unwrap().iter()
489 .filter(|e| e.is_ipv6() && e.port() == 8333)
490 .choose_multiple(&mut rng, 12).iter().map(|e| e.ip()).collect();
493 dns_buff += &format!("x{:x}.dnsseed\tIN\tA\t{}\n", i, a);
496 dns_buff += &format!("x{:x}.dnsseed\tIN\tAAAA\t{}\n", i, a);
500 write_all(f, dns_buff)
501 }).and_then(|(mut f, _)| {
504 tokio::fs::rename(dns_file.clone() + ".tmp", dns_file)
507 settings_future.join3(nodes_future, dns_future).then(|_| { future::ok(()) })
510 pub fn get_next_scan_nodes(&self) -> Vec<SocketAddr> {
511 let results = 30 * self.get_u64(U64Setting::ConnsPerSec) as usize;
512 let per_bucket_results = results / (AddressState::get_count() as usize);
513 let mut res = Vec::with_capacity(results);
514 let cur_time = Instant::now();
517 let mut nodes = self.nodes.write().unwrap();
518 for (idx, state_nodes) in nodes.state_next_scan.iter_mut().enumerate() {
519 let cmp_time = cur_time - Duration::from_secs(self.get_u64(U64Setting::RescanInterval(AddressState::from_num(idx as u8).unwrap())));
520 let split_point = cmp::min(cmp::min(results - res.len(), (per_bucket_results * (idx + 1)) - res.len()),
521 state_nodes.binary_search_by(|a| a.0.cmp(&cmp_time)).unwrap_or_else(|idx| idx));
522 let mut new_nodes = state_nodes.split_off(split_point);
523 mem::swap(&mut new_nodes, state_nodes);
524 for (_, node) in new_nodes.drain(..) {
529 res.shuffle(&mut thread_rng());