Fixed multiple clippy warnings.

pull/195/head
Revertron 2 years ago
parent d776cca5b3
commit 797584c516

@ -47,6 +47,7 @@ impl Block {
}
}
#[allow(clippy::too_many_arguments)]
pub fn from_all_params(index: u64, timestamp: i64, version: u32, difficulty: u32, random: u32, nonce: u64, prev_block_hash: Bytes, hash: Bytes, pub_key: Bytes, signature: Bytes, transaction: Option<Transaction>) -> Self {
Block {
index,

@ -81,6 +81,7 @@ impl Chain {
if !self.origin.is_zero() && !options.origin.is_empty() && self.origin.to_string() != options.origin {
self.clear_db();
}
#[allow(clippy::absurd_extreme_comparisons)]
if options.version < DB_VERSION {
self.migrate_db(options.version, DB_VERSION);
}
@ -278,7 +279,7 @@ impl Chain {
Ok(())
}
pub fn get_sign_block(&self, keys: &Vec<Keystore>) -> Option<(Block, Keystore)> {
pub fn get_sign_block(&self, keys: &[Keystore]) -> Option<(Block, Keystore)> {
if self.get_height() < BLOCK_SIGNERS_START {
trace!("Too early to start block signings");
return None;
@ -419,7 +420,7 @@ impl Chain {
match self.db.prepare(SQL_GET_BLOCK_BY_ID) {
Ok(mut statement) => {
statement.bind(1, index as i64).expect("Error in bind");
while statement.next().unwrap() == State::Row {
if statement.next().unwrap() == State::Row {
return match Self::get_block_from_statement(&mut statement) {
None => {
error!("Something wrong with block in DB!");
@ -470,7 +471,7 @@ impl Chain {
statement
}
};
while statement.next().unwrap() == State::Row {
if statement.next().unwrap() == State::Row {
return match Self::get_block_from_statement(&mut statement) {
None => {
error!("Something wrong with block in DB!");
@ -495,10 +496,10 @@ impl Chain {
return false;
}
let parts: Vec<&str> = domain.rsplitn(2, ".").collect();
let parts: Vec<&str> = domain.rsplitn(2, '.').collect();
if parts.len() > 1 {
// We do not support third level domains
if parts.last().unwrap().contains(".") {
if parts.last().unwrap().contains('.') {
return false;
}
return self.is_available_zone(parts.first().unwrap());
@ -527,7 +528,7 @@ impl Chain {
fn load_zones() -> Vec<ZoneData> {
let mut result: Vec<ZoneData> = Vec::new();
let zones_text = ZONES_TXT.replace("\r", "");
let zones: Vec<_> = zones_text.split("\n").collect();
let zones: Vec<_> = zones_text.split('\n').collect();
for zone in zones {
let yggdrasil = zone == "ygg" || zone == "anon";
result.push(ZoneData { name: zone.to_owned(), yggdrasil })
@ -536,7 +537,7 @@ impl Chain {
}
pub fn get_zones_hash() -> Bytes {
Bytes::from_bytes(hash_sha256(&ZONES_TXT.as_bytes()).as_slice())
Bytes::from_bytes(hash_sha256(ZONES_TXT.as_bytes()).as_slice())
}
/// Checks if some zone exists in our blockchain
@ -556,7 +557,7 @@ impl Chain {
let mut statement = self.db.prepare(SQL_GET_DOMAIN_OWNER_BY_ID).unwrap();
statement.bind(1, height as i64).expect("Error in bind");
statement.bind(2, &***id).expect("Error in bind");
while let State::Row = statement.next().unwrap() {
if let State::Row = statement.next().unwrap() {
// If there is such a zone
return true;
}
@ -579,7 +580,7 @@ impl Chain {
}
let identity_hash = hash_identity(&name, None);
// TODO extract method
if let Some(last) = self.get_last_full_block(MAX, Some(&pub_key)) {
if let Some(last) = self.get_last_full_block(MAX, Some(pub_key)) {
let new_id = !self.is_domain_in_blockchain(height, &identity_hash);
let time = last.timestamp + NEW_DOMAINS_INTERVAL - Utc::now().timestamp();
if new_id && time > 0 {
@ -593,7 +594,7 @@ impl Chain {
pub fn get_id_transaction(&self, identity_hash: &Bytes) -> Option<Transaction> {
let mut statement = self.db.prepare(SQL_GET_DOMAIN_BY_ID).unwrap();
statement.bind(1, identity_hash.as_slice()).expect("Error in bind");
while let State::Row = statement.next().unwrap() {
if let State::Row = statement.next().unwrap() {
let timestamp = statement.read::<i64>(1).unwrap();
if timestamp < Utc::now().timestamp() - DOMAIN_LIFETIME {
// This domain is too old
@ -635,7 +636,7 @@ impl Chain {
pub fn get_domains_count(&self) -> i64 {
let mut statement = self.db.prepare(SQL_GET_DOMAINS_COUNT).unwrap();
while let State::Row = statement.next().unwrap() {
if let State::Row = statement.next().unwrap() {
return statement.read::<i64>(0).unwrap();
}
0
@ -643,7 +644,7 @@ impl Chain {
pub fn get_users_count(&self) -> i64 {
let mut statement = self.db.prepare(SQL_GET_USERS_COUNT).unwrap();
while let State::Row = statement.next().unwrap() {
if let State::Row = statement.next().unwrap() {
return statement.read::<i64>(0).unwrap();
}
0
@ -665,7 +666,7 @@ impl Chain {
}
let mut result = HashMap::new();
let keystore = keystore.clone().unwrap();
let keystore = keystore.unwrap();
let pub_key = keystore.get_public();
let mut statement = self.db.prepare(SQL_GET_DOMAINS_BY_KEY).unwrap();
statement.bind(1, &**pub_key).expect("Error in bind");
@ -785,7 +786,7 @@ impl Chain {
SIGNER_DIFFICULTY
}
}
Some(t) => self.get_difficulty_for_transaction(&t, block.index)
Some(t) => self.get_difficulty_for_transaction(t, block.index)
};
if block.difficulty < difficulty {
warn!("Block difficulty is lower than needed");
@ -799,7 +800,7 @@ impl Chain {
warn!("Ignoring block with wrong hash:\n{:?}", &block);
return Bad;
}
if !check_block_signature(&block) {
if !check_block_signature(block) {
warn!("Ignoring block with wrong signature:\n{:?}", &block);
return Bad;
}
@ -843,19 +844,17 @@ impl Chain {
}
let zones = self.get_zones();
for z in zones {
if z.name == block_data.zone {
if z.yggdrasil {
for record in &block_data.records {
if !is_yggdrasil_record(record) {
warn!("Someone mined domain with clearnet records for Yggdrasil only zone!");
if z.name == block_data.zone && z.yggdrasil {
for record in &block_data.records {
if !is_yggdrasil_record(record) {
warn!("Someone mined domain with clearnet records for Yggdrasil only zone!");
return Bad;
}
if let Some(data) = record.get_data() {
if data.len() > MAX_DATA_LEN {
warn!("Someone mined too long record!");
return Bad;
}
if let Some(data) = record.get_data() {
if data.len() > MAX_DATA_LEN {
warn!("Someone mined too long record!");
return Bad;
}
}
}
}
}
@ -884,7 +883,7 @@ impl Chain {
}
if block.index > BLOCK_SIGNERS_START {
// If this block is main, signed part of blockchain
if !self.is_good_sign_block(&block, last_full_block) {
if !self.is_good_sign_block(block, last_full_block) {
return Bad;
}
}
@ -926,15 +925,12 @@ impl Chain {
if block.index > full_block.index && block.transaction.is_some() {
warn!("Not enough signing blocks over full {} block!", full_block.index);
return false;
} else {
if !self.is_good_signer_for_block(&block, full_block) {
return false;
}
}
} else if sign_count < BLOCK_SIGNERS_ALL && block.transaction.is_none() {
if !self.is_good_signer_for_block(&block, full_block) {
} else if !self.is_good_signer_for_block(block, full_block) {
return false;
}
} else if sign_count < BLOCK_SIGNERS_ALL && block.transaction.is_none()
&& !self.is_good_signer_for_block(block, full_block) {
return false;
}
}
true

@ -25,7 +25,7 @@ impl DnsFilter for BlockchainFilter {
fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
let search;
let subdomain;
let parts: Vec<&str> = qname.rsplitn(3, ".").collect();
let parts: Vec<&str> = qname.rsplitn(3, '.').collect();
match parts.len() {
1 => {
let mut packet = DnsPacket::new();
@ -193,10 +193,10 @@ impl BlockchainFilter {
});
}
fn get_zone_response(&self, zone: &str, serial: u32, mut packet: &mut DnsPacket) -> bool {
fn get_zone_response(&self, zone: &str, serial: u32, packet: &mut DnsPacket) -> bool {
let have_zone = self.context.lock().unwrap().chain.is_available_zone(zone);
if have_zone {
BlockchainFilter::add_soa_record(zone.to_owned(), serial, &mut packet);
BlockchainFilter::add_soa_record(zone.to_owned(), serial, packet);
}
have_zone
}

@ -30,13 +30,13 @@ pub fn check_block_signature(block: &Block) -> bool {
/// Hashes some identity (domain in case of DNS). If you give it a public key, it will hash with it as well.
/// Giving public key is needed to create a confirmation field in [Transaction](crate::blockchain::Transaction)
pub fn hash_identity(identity: &str, key: Option<&Bytes>) -> Bytes {
let base = hash_sha256(identity.as_bytes());
let mut base = hash_sha256(identity.as_bytes());
let identity = hash_sha256(&base);
match key {
None => Bytes::from_bytes(&identity),
Some(key) => {
let mut buf = Vec::new();
buf.append(&mut base.clone());
buf.append(&mut base);
buf.append(&mut key.to_vec());
Bytes::from_bytes(&hash_sha256(&buf))
}

@ -30,7 +30,7 @@ impl Transaction {
pub fn from_str(identity: String, method: String, data: String, signing: Bytes, encryption: Bytes) -> Self {
let hash = hash_identity(&identity, None);
let confirmation = hash_identity(&identity, Some(&signing));
return Self::new(hash, confirmation, method, data, signing, encryption);
Self::new(hash, confirmation, method, data, signing, encryption)
}
pub fn new(identity: Bytes, confirmation: Bytes, method: String, data: String, signing: Bytes, encryption: Bytes) -> Self {
@ -49,14 +49,15 @@ impl Transaction {
}
}
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
// Let it panic if something is not okay
serde_json::to_string(&self).unwrap()
}
pub fn check_identity(&self, domain: &str) -> bool {
let hash = hash_identity(&domain, None);
let confirmation = hash_identity(&domain, Some(&self.signing));
let hash = hash_identity(domain, None);
let confirmation = hash_identity(domain, Some(&self.signing));
self.identity.eq(&hash) && self.confirmation.eq(&confirmation)
}

@ -13,7 +13,7 @@ use num_bigint::BigUint;
use serde::de::{Error as DeError, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone)]
#[derive(Clone, Default)]
pub struct Bytes {
data: Vec<u8>
}
@ -44,7 +44,7 @@ impl Bytes {
return false;
}
}
return true;
true
}
/// Returns a byte slice of the hash contents.
@ -57,6 +57,7 @@ impl Bytes {
self.data.as_mut_slice()
}
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
crate::commons::to_hex(&self.data)
}
@ -76,19 +77,9 @@ impl Bytes {
}
}
impl Default for Bytes {
fn default() -> Bytes {
Bytes { data: Vec::new() }
}
}
impl PartialEq for Bytes {
fn eq(&self, other: &Self) -> bool {
crate::blockchain::hash_utils::same_hash(&self, &other)
}
fn ne(&self, other: &Self) -> bool {
!crate::blockchain::hash_utils::same_hash(&self, &other)
crate::blockchain::hash_utils::same_hash(self, other)
}
}
@ -96,16 +87,16 @@ impl Eq for Bytes {}
impl PartialOrd for Bytes {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
let self_hash_int = BigUint::from_bytes_le(&self);
let other_hash_int = BigUint::from_bytes_le(&other);
let self_hash_int = BigUint::from_bytes_le(self);
let other_hash_int = BigUint::from_bytes_le(other);
Some(self_hash_int.cmp(&other_hash_int))
}
}
impl Ord for Bytes {
fn cmp(&self, other: &Self) -> Ordering {
let self_hash_int = BigUint::from_bytes_le(&self);
let other_hash_int = BigUint::from_bytes_le(&other);
let self_hash_int = BigUint::from_bytes_le(self);
let other_hash_int = BigUint::from_bytes_le(other);
self_hash_int.cmp(&other_hash_int)
}
}

@ -22,7 +22,7 @@ pub const BLOCK_SIGNERS_MIN: u64 = 4;
pub const LIMITED_CONFIDENCE_DEPTH: u64 = 4;
/// We start mining signing blocks after random delay, this is the max delay
pub const BLOCK_SIGNERS_START_RANDOM: i64 = 180;
pub const BLOCK_SIGNERS_START_RANDOM: i64 = 90;
pub const NEW_DOMAINS_INTERVAL: i64 = 86400; // One day in seconds
pub const DOMAIN_LIFETIME: i64 = 86400 * 365; // One year

@ -22,7 +22,7 @@ pub fn to_hex(buf: &[u8]) -> String {
}
pub fn from_hex(string: &str) -> Result<Vec<u8>, num::ParseIntError> {
split_n(&string.trim()[..], 2)
split_n(string.trim(), 2)
.iter()
.map(|b| u8::from_str_radix(b, 16))
.collect()
@ -32,11 +32,9 @@ pub fn check_domain(name: &str, allow_dots: bool) -> bool {
if name.starts_with('.') || name.starts_with('-') || name.ends_with('.') || name.ends_with('-') {
return false;
}
let parts: Vec<&str> = name.rsplitn(2, ".").collect();
if parts.len() == 2 {
if parts[1].len() < 3 && is_numeric(parts[1]) {
return false;
}
let parts: Vec<&str> = name.rsplitn(2, '.').collect();
if parts.len() == 2 && parts[1].len() < 3 && is_numeric(parts[1]) {
return false;
}
let mut last_dot = false;
@ -77,7 +75,7 @@ pub fn is_numeric(str: &str) -> bool {
}
pub fn get_domain_zone(domain: &str) -> String {
let parts: Vec<&str> = domain.rsplitn(2, ".").collect();
let parts: Vec<&str> = domain.rsplitn(2, '.').collect();
if !parts.is_empty() {
parts[0].to_owned()
} else {

@ -2,7 +2,9 @@ use std::collections::HashMap;
use uuid::Uuid;
#[derive(Default)]
pub struct Bus<T> {
#[allow(clippy::type_complexity)]
listeners: HashMap<Uuid, Box<dyn FnMut(&Uuid, T) -> bool + Send + Sync>>
}
@ -13,12 +15,12 @@ impl<T: Clone> Bus<T> {
pub fn register<F>(&mut self, closure: F) -> Uuid where F: FnMut(&Uuid, T) -> bool + Send + Sync + 'static {
let uuid = Uuid::new_v4();
self.listeners.insert(uuid.clone(), Box::new(closure));
self.listeners.insert(uuid, Box::new(closure));
uuid
}
pub fn unregister(&mut self, uuid: &Uuid) {
self.listeners.remove(&uuid);
self.listeners.remove(uuid);
}
pub fn post(&mut self, event: T) {

@ -23,12 +23,12 @@ impl Chacha {
}
pub fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
let nonce = Nonce::from(self.nonce.clone());
let nonce = Nonce::from(self.nonce);
self.cipher.encrypt(&nonce, data.as_ref())
}
pub fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
let nonce = Nonce::from(self.nonce.clone());
let nonce = Nonce::from(self.nonce);
self.cipher.decrypt(&nonce, data.as_ref())
}

@ -46,7 +46,7 @@ impl CryptoBox {
pub fn decrypt(secret: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
let secret = SecretKey::from_bytes(secret).unwrap();
decrypt(&secret, &message)
decrypt(&secret, message)
}
}

@ -39,9 +39,9 @@ pub struct Zone {
impl Zone {
pub fn new(domain: String, m_name: String, r_name: String) -> Zone {
Zone {
domain: domain,
m_name: m_name,
r_name: r_name,
domain,
m_name,
r_name,
serial: 0,
refresh: 0,
retry: 0,
@ -222,7 +222,7 @@ impl Authority {
None => continue
};
if &domain != qname {
if domain != qname {
continue;
}

@ -49,7 +49,7 @@ pub trait PacketBuffer {
self.write(((val >> 24) & 0xFF) as u8)?;
self.write(((val >> 16) & 0xFF) as u8)?;
self.write(((val >> 8) & 0xFF) as u8)?;
self.write(((val >> 0) & 0xFF) as u8)?;
self.write((val & 0xFF) as u8)?;
Ok(())
}
@ -95,7 +95,7 @@ pub trait PacketBuffer {
let res = ((self.read()? as u32) << 24)
| ((self.read()? as u32) << 16)
| ((self.read()? as u32) << 8)
| ((self.read()? as u32) << 0);
| (self.read()? as u32);
Ok(res)
}
@ -239,7 +239,7 @@ impl<'a, T> PacketBuffer for StreamPacketBuffer<'a, T> where T: Read + 'a {
fn read(&mut self) -> Result<u8> {
while self.pos >= self.buffer.len() {
let mut local_buffer = [0; 1];
self.stream.read(&mut local_buffer)?;
self.stream.read_exact(&mut local_buffer)?;
self.buffer.push(local_buffer[0]);
}
@ -252,7 +252,7 @@ impl<'a, T> PacketBuffer for StreamPacketBuffer<'a, T> where T: Read + 'a {
fn get(&mut self, pos: usize) -> Result<u8> {
while pos >= self.buffer.len() {
let mut local_buffer = [0; 1];
self.stream.read(&mut local_buffer)?;
self.stream.read_exact(&mut local_buffer)?;
self.buffer.push(local_buffer[0]);
}
@ -262,7 +262,7 @@ impl<'a, T> PacketBuffer for StreamPacketBuffer<'a, T> where T: Read + 'a {
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
while start + len > self.buffer.len() {
let mut local_buffer = [0; 1];
self.stream.read(&mut local_buffer)?;
self.stream.read_exact(&mut local_buffer)?;
self.buffer.push(local_buffer[0]);
}

@ -131,7 +131,7 @@ impl DnsNetworkClient {
let mut socket = TcpStream::connect(server)?;
write_packet_length(&mut socket, req_buffer.pos())?;
socket.write(&req_buffer.buf[0..req_buffer.pos])?;
socket.write_all(&req_buffer.buf[0..req_buffer.pos])?;
socket.flush()?;
let _ = read_packet_length(&mut socket)?;
@ -409,7 +409,7 @@ impl HttpsDnsClient {
.max_idle_connections_per_host(8)
.max_idle_connections(16)
.resolver(move |addr: &str| {
let addr = match addr.find(":") {
let addr = match addr.find(':') {
Some(index) => addr[0..index].to_string(),
None => addr.to_string()
};
@ -427,17 +427,15 @@ impl HttpsDnsClient {
for server in &servers {
if let Ok(res) = dns_client.send_udp_query(&addr, QueryType::A, server, true) {
for answer in &res.answers {
match answer {
DnsRecord::A { addr, .. } => result.push(IpAddr::V4(addr.clone())),
_ => {}
if let DnsRecord::A { addr, .. } = answer {
result.push(IpAddr::V4(*addr))
}
}
}
if let Ok(res) = dns_client.send_udp_query(&addr, QueryType::AAAA, server, true) {
for answer in &res.answers {
match answer {
DnsRecord::AAAA { addr, .. } => result.push(IpAddr::V6(addr.clone())),
_ => {}
if let DnsRecord::AAAA { addr, .. } = answer {
result.push(IpAddr::V6(*addr))
}
}
}
@ -496,7 +494,7 @@ impl DnsClient for HttpsDnsClient {
let response = self.agent
.post(doh_url)
.set("Content-Type", "application/dns-message")
.send_bytes(&req_buffer.buffer.as_slice());
.send_bytes(req_buffer.buffer.as_slice());
match response {
Ok(response) => {
@ -512,7 +510,7 @@ impl DnsClient for HttpsDnsClient {
.take(4096)
.read_to_end(&mut bytes)?;
let mut buffer = VectorPacketBuffer::new();
buffer.buffer.extend_from_slice(&bytes.as_slice());
buffer.buffer.extend_from_slice(bytes.as_slice());
if let Ok(packet) = DnsPacket::from_buffer(&mut buffer) {
return Ok(packet);
}

@ -20,13 +20,13 @@ impl HostsFilter {
file.read_to_string(&mut text).unwrap();
let mut map = HashMap::new();
let list: Vec<_> = text.split("\n").collect();
let list: Vec<_> = text.split('\n').collect();
for s in list {
if s.is_empty() || s.starts_with("#") {
if s.is_empty() || s.starts_with('#') {
continue;
}
let string = s.replace('\t', " ");
let parts: Vec<_> = string.splitn(2, " ").collect();
let parts: Vec<_> = string.splitn(2, ' ').collect();
if parts.len() != 2 {
continue;
}
@ -34,6 +34,7 @@ impl HostsFilter {
let domain = parts[1].trim().to_owned();
if let Ok(addr) = ip.parse::<IpAddr>() {
if !domain.is_empty() {
#[allow(clippy::or_fun_call)]
map.entry(domain).or_insert(vec![addr]);
}
}
@ -58,10 +59,10 @@ impl DnsFilter for HostsFilter {
for addr in list {
match addr {
IpAddr::V4(addr) if qtype == QueryType::A => {
packet.answers.push(DnsRecord::A { domain: qname.to_owned(), addr: addr.clone(), ttl: TransientTtl(2) });
packet.answers.push(DnsRecord::A { domain: qname.to_owned(), addr: *addr, ttl: TransientTtl(2) });
}
IpAddr::V6(addr) if qtype == QueryType::AAAA => {
packet.answers.push(DnsRecord::AAAA { domain: qname.to_owned(), addr: addr.clone(), ttl: TransientTtl(2) });
packet.answers.push(DnsRecord::AAAA { domain: qname.to_owned(), addr: *addr, ttl: TransientTtl(2) });
}
_ => {}
}

@ -3,7 +3,7 @@ use std::net::TcpStream;
pub fn read_packet_length(stream: &mut TcpStream) -> Result<u16> {
let mut len_buffer = [0; 2];
stream.read(&mut len_buffer)?;
stream.read_exact(&mut len_buffer)?;
Ok(((len_buffer[0] as u16) << 8) | (len_buffer[1] as u16))
}
@ -13,7 +13,7 @@ pub fn write_packet_length(stream: &mut TcpStream, len: usize) -> Result<()> {
len_buffer[0] = (len >> 8) as u8;
len_buffer[1] = (len & 0xFF) as u8;
stream.write(&len_buffer)?;
stream.write_all(&len_buffer)?;
Ok(())
}

@ -1,7 +1,5 @@
//! implements the DNS protocol in a transport agnostic fashion
//use std::io::{Error, ErrorKind};
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::net::{Ipv4Addr, Ipv6Addr};
@ -78,18 +76,12 @@ impl QueryType {
}
}
#[derive(Copy, Clone, Debug, Eq, Ord, Serialize, Deserialize)]
#[derive(Copy, Clone, Debug, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TransientTtl(pub u32);
impl PartialEq<TransientTtl> for TransientTtl {
fn eq(&self, _: &TransientTtl) -> bool {
true
}
}
impl PartialOrd<TransientTtl> for TransientTtl {
fn partial_cmp(&self, _: &TransientTtl) -> Option<Ordering> {
Some(Ordering::Equal)
fn eq(&self, other: &TransientTtl) -> bool {
self.0 == other.0
}
}
@ -200,7 +192,7 @@ impl DnsRecord {
((raw_addr >> 24) & 0xFF) as u8,
((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8
(raw_addr & 0xFF) as u8
);
Ok(DnsRecord::A { domain, addr, ttl: TransientTtl(ttl) })
@ -212,13 +204,13 @@ impl DnsRecord {
let raw_addr4 = buffer.read_u32()?;
let addr = Ipv6Addr::new(
((raw_addr1 >> 16) & 0xFFFF) as u16,
((raw_addr1 >> 0) & 0xFFFF) as u16,
(raw_addr1 & 0xFFFF) as u16,
((raw_addr2 >> 16) & 0xFFFF) as u16,
((raw_addr2 >> 0) & 0xFFFF) as u16,
(raw_addr2 & 0xFFFF) as u16,
((raw_addr3 >> 16) & 0xFFFF) as u16,
((raw_addr3 >> 0) & 0xFFFF) as u16,
(raw_addr3 & 0xFFFF) as u16,
((raw_addr4 >> 16) & 0xFFFF) as u16,
((raw_addr4 >> 0) & 0xFFFF) as u16
(raw_addr4 & 0xFFFF) as u16
);
Ok(DnsRecord::AAAA { domain, addr, ttl: TransientTtl(ttl) })
@ -578,7 +570,7 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
_ => ResultCode::NOERROR
}
}
}
@ -642,7 +634,7 @@ impl DnsHeader {
)?;
buffer.write_u8(
(self.rescode.clone() as u8)
(self.rescode as u8)
| ((self.checking_disabled as u8) << 4)
| ((self.authed_data as u8) << 5)
| ((self.z as u8) << 6)
@ -691,25 +683,25 @@ impl DnsHeader {
impl fmt::Display for DnsHeader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DnsHeader:\n")?;
write!(f, "\tid: {0}\n", self.id)?;
write!(f, "\trecursion_desired: {0}\n", self.recursion_desired)?;
write!(f, "\ttruncated_message: {0}\n", self.truncated_message)?;
write!(f, "\tauthoritative_answer: {0}\n", self.authoritative_answer)?;
write!(f, "\topcode: {0}\n", self.opcode)?;
write!(f, "\tresponse: {0}\n", self.response)?;
write!(f, "\trescode: {:?}\n", self.rescode)?;
write!(f, "\tchecking_disabled: {0}\n", self.checking_disabled)?;
write!(f, "\tauthed_data: {0}\n", self.authed_data)?;
write!(f, "\tz: {0}\n", self.z)?;
write!(f, "\trecursion_available: {0}\n", self.recursion_available)?;
write!(f, "\tquestions: {0}\n", self.questions)?;
write!(f, "\tanswers: {0}\n", self.answers)?;
write!(f, "\tauthoritative_entries: {0}\n", self.authoritative_entries)?;
write!(f, "\tresource_entries: {0}\n", self.resource_entries)?;
writeln!(f, "DnsHeader:")?;
writeln!(f, "\tid: {0}", self.id)?;
writeln!(f, "\trecursion_desired: {0}", self.recursion_desired)?;
writeln!(f, "\ttruncated_message: {0}", self.truncated_message)?;
writeln!(f, "\tauthoritative_answer: {0}", self.authoritative_answer)?;
writeln!(f, "\topcode: {0}", self.opcode)?;
writeln!(f, "\tresponse: {0}", self.response)?;
writeln!(f, "\trescode: {:?}", self.rescode)?;
writeln!(f, "\tchecking_disabled: {0}", self.checking_disabled)?;
writeln!(f, "\tauthed_data: {0}", self.authed_data)?;
writeln!(f, "\tz: {0}", self.z)?;
writeln!(f, "\trecursion_available: {0}", self.recursion_available)?;
writeln!(f, "\tquestions: {0}", self.questions)?;
writeln!(f, "\tanswers: {0}", self.answers)?;
writeln!(f, "\tauthoritative_entries: {0}", self.authoritative_entries)?;
writeln!(f, "\tresource_entries: {0}", self.resource_entries)?;
Ok(())
}
@ -752,9 +744,9 @@ impl DnsQuestion {
impl fmt::Display for DnsQuestion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DnsQuestion:\n")?;
write!(f, "\tname: {0}\n", self.name)?;
write!(f, "\trecord type: {:?}\n", self.qtype)?;
writeln!(f, "DnsQuestion:")?;
writeln!(f, "\tname: {0}", self.name)?;
writeln!(f, "\trecord type: {:?}", self.qtype)?;
Ok(())
}
@ -946,7 +938,7 @@ impl DnsPacket {
let mut test_buffer = VectorPacketBuffer::new();
let mut size = self.header.binary_len();
for ref question in &self.questions {
for question in &self.questions {
size += question.binary_len();
question.write(&mut test_buffer)?;
}

@ -153,7 +153,7 @@ impl DnsResolver for RecursiveDnsResolver {
}
}
let mut ns = tentative_ns.ok_or_else(|| ResolveError::NoServerFound)?;
let mut ns = tentative_ns.ok_or(ResolveError::NoServerFound)?;
// Start querying name servers
loop {
@ -162,21 +162,21 @@ impl DnsResolver for RecursiveDnsResolver {
let ns_copy = ns.clone();
let server = format!("{}:{}", ns_copy.as_str(), 53);
let response = self.context.old_client.send_query(qname, qtype.clone(), &server, false)?;
let response = self.context.old_client.send_query(qname, qtype, &server, false)?;
// If we've got an actual answer, we're done!
if !response.answers.is_empty() && response.header.rescode == ResultCode::NOERROR {
let _ = self.context.cache.store(&response.answers);
let _ = self.context.cache.store(&response.authorities);
let _ = self.context.cache.store(&response.resources);
return Ok(response.clone());
return Ok(response);
}
if response.header.rescode == ResultCode::NXDOMAIN {
if let Some(ttl) = response.get_ttl_from_soa() {
let _ = self.context.cache.store_nxdomain(qname, qtype, ttl);
}
return Ok(response.clone());
return Ok(response);
}
// Otherwise, try to find a new nameserver based on NS and a
@ -194,7 +194,7 @@ impl DnsResolver for RecursiveDnsResolver {
// If not, we'll have to resolve the ip of a NS record
let new_ns_name = match response.get_unresolved_ns(qname) {
Some(x) => x,
None => return Ok(response.clone())
None => return Ok(response)
};
// Recursively resolve the NS
@ -204,7 +204,7 @@ impl DnsResolver for RecursiveDnsResolver {
if let Some(new_ns) = recursive_response.get_random_a() {
ns = new_ns.clone();
} else {
return Ok(response.clone());
return Ok(response);
}
}
}

@ -67,8 +67,8 @@ fn resolve_cnames(lookup_list: &[DnsRecord], results: &mut Vec<DnsPacket>, resol
return;
}
for ref rec in lookup_list {
match **rec {
for rec in lookup_list {
match *rec {
DnsRecord::CNAME { ref host, .. } | DnsRecord::SRV { ref host, .. } => {
if let Ok(result2) = resolver.resolve(host, qtype, true) {
let new_unmatched = result2.get_unresolved_cnames(qtype);
@ -268,7 +268,7 @@ impl DnsServer for DnsUdpServer {
}
};
// If we got a request resent in 100ms interval, then we just skip it
let key = (src.clone(), request.header.id);
let key = (src, request.header.id);
let cur_time = Utc::now().timestamp_millis();
if let Some(time) = working_ids.get(&key) {
if time + 100 > cur_time {

@ -12,7 +12,7 @@ use crate::{Context, Settings};
/// Starts UDP and TCP DNS-servers
pub fn start_dns_server(context: &Arc<Mutex<Context>>, settings: &Settings) -> bool {
let server_context = create_server_context(Arc::clone(&context), &settings);
let server_context = create_server_context(Arc::clone(context), settings);
let mut result = true;
if server_context.enable_udp {

@ -60,7 +60,7 @@ impl Keystore {
}
pub fn from_random_bytes(key: &[u8]) -> Self {
let secret = SecretKey::from_bytes(&key).unwrap();
let secret = SecretKey::from_bytes(key).unwrap();
let public = PublicKey::from(&secret);
let keypair = Keypair { secret, public };
let mut csprng = rand_old::thread_rng();
@ -147,10 +147,7 @@ impl Keystore {
pub fn check(message: &[u8], public_key: &[u8], signature: &[u8]) -> bool {
let key = PublicKey::from_bytes(public_key).expect("Wrong public key!");
let signature = Signature::from_bytes(signature).unwrap();
match key.verify(message, &signature) {
Ok(_) => true,
Err(_) => false
}
key.verify(message, &signature).is_ok()
}
pub fn encrypt(&self, message: &[u8]) -> Bytes {
@ -169,6 +166,12 @@ impl Keystore {
}
}
impl Default for Keystore {
fn default() -> Self {
Self::new()
}
}
impl Clone for Keystore {
fn clone(&self) -> Self {
let keypair = Keypair::from_bytes(&self.keypair.to_bytes()).unwrap();
@ -185,7 +188,7 @@ impl PartialEq for Keystore {
/// Checks if some public key is "strong" enough to mine domains
/// TODO Optimize by caching Blakeout somewhere
pub fn check_public_key_strength(key: &Bytes, strength: u32) -> bool {
let bytes = blakeout_data(&key);
let bytes = blakeout_data(key);
key_hash_difficulty(&bytes) >= strength
}

@ -103,7 +103,7 @@ fn main() {
let no_gui = true;
if let Some(path) = opt_matches.opt_str("w") {
env::set_current_dir(Path::new(&path)).expect(&format!("Unable to change working directory to '{}'", &path));
env::set_current_dir(Path::new(&path)).unwrap_or_else(|_| panic!("Unable to change working directory to '{}'", &path));
}
let config_name = match opt_matches.opt_str("c") {
None => SETTINGS_FILENAME.to_owned(),
@ -113,18 +113,16 @@ fn main() {
setup_logger(&opt_matches, console_attached);
if let Some(status) = opt_matches.opt_str("s") {
register(move |_, event| {
match event {
Event::NetworkStatus { blocks, domains, keys, nodes } => {
match File::create(Path::new(&status)) {
Ok(mut f) => {
let data = format!("{{ \"blocks\":{}, \"domains\":{}, \"keys\":{}, \"nodes\":{} }}", blocks, domains, keys, nodes);
f.write_all(data.as_bytes()).expect("Error writing status file!");
let _ = f.flush();
}
Err(_) => { error!("Error writing status file!"); }
// TODO optimize for same data
if let Event::NetworkStatus { blocks, domains, keys, nodes } = event {
match File::create(Path::new(&status)) {
Ok(mut f) => {
let data = format!("{{ \"blocks\":{}, \"domains\":{}, \"keys\":{}, \"nodes\":{} }}", blocks, domains, keys, nodes);
f.write_all(data.as_bytes()).expect("Error writing status file!");
let _ = f.flush();
}
Err(_) => { error!("Error writing status file!"); }
}
_ => {}
}
true
});
@ -132,7 +130,7 @@ fn main() {
info!(target: LOG_TARGET_MAIN, "Starting ALFIS {}", env!("CARGO_PKG_VERSION"));
let settings = Settings::load(&config_name).expect(&format!("Cannot load settings from {}!", &config_name));
let settings = Settings::load(&config_name).unwrap_or_else(|| panic!("Cannot load settings from {}!", &config_name));
debug!(target: LOG_TARGET_MAIN, "Loaded settings: {:?}", &settings);
let chain: Chain = Chain::new(&settings, DB_NAME);
if opt_matches.opt_present("b") {
@ -146,7 +144,7 @@ fn main() {
info!("Blocks count: {}, domains count: {}, users count: {}", chain.get_height(), chain.get_domains_count(), chain.get_users_count());
let settings_copy = settings.clone();
let mut keys = Vec::new();
if settings.key_files.len() > 0 {
if !settings.key_files.is_empty() {
for name in &settings.key_files {
match Keystore::from_file(name, "") {
None => {
@ -239,7 +237,7 @@ fn main() {
});
}
#[cfg(feature = "webgui")]
web_ui::run_interface(Arc::clone(&context), miner.clone());
web_ui::run_interface(Arc::clone(&context), miner);
}
// Without explicitly detaching the console cmd won't redraw it's prompt.
@ -292,10 +290,8 @@ fn setup_logger(opt_matches: &Matches, console_attached: bool) {
WriteLogger::new(level, config, file),
])
.unwrap();
} else {
if let Err(e) = WriteLogger::init(level, config, file) {
println!("Unable to initialize logger!\n{}", e);
}
} else if let Err(e) = WriteLogger::init(level, config, file) {
println!("Unable to initialize logger!\n{}", e);
}
}
}

@ -138,7 +138,7 @@ impl Miner {
mining.store(true, Ordering::SeqCst);
current_job = Some(job.clone());
Miner::mine_internal(Arc::clone(&context), job, mining.clone());
Miner::mine_internal(Arc::clone(context), job, mining.clone());
continue;
} else {
debug!("This job will wait for now");
@ -159,7 +159,7 @@ impl Miner {
}
}
}
let _ = cond_var.wait_timeout(jobs, delay).expect("Error in wait lock!");
let _lock = cond_var.wait_timeout(jobs, delay).expect("Error in wait lock!");
}
} else {
let mut jobs = jobs.lock().unwrap();
@ -169,7 +169,7 @@ impl Miner {
if job.is_due() {
mining.store(true, Ordering::SeqCst);
current_job = Some(job.clone());
Miner::mine_internal(Arc::clone(&context), job, mining.clone());
Miner::mine_internal(Arc::clone(context), job, mining.clone());
} else {
debug!("This job will wait for now");
jobs.insert(0, job);
@ -187,7 +187,7 @@ impl Miner {
}
}
}
let _ = cond_var.wait_timeout(jobs, delay).expect("Error in wait lock!");
let _lock = cond_var.wait_timeout(jobs, delay).expect("Error in wait lock!");
}
if !mining.load(Ordering::Relaxed) {

@ -2,6 +2,7 @@ extern crate serde;
extern crate serde_json;
use serde::{Deserialize, Serialize};
use serde_cbor::Error;
use crate::Bytes;
@ -21,11 +22,8 @@ pub enum Message {
}
impl Message {
pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, ()> {
match serde_cbor::from_slice(bytes.as_slice()) {
Ok(cmd) => Ok(cmd),
Err(_) => Err(())
}
pub fn from_bytes(bytes: Vec<u8>) -> Result<Message, Error> {
serde_cbor::from_slice(bytes.as_slice())
}
pub fn hand(app_version: &str, origin: &str, version: u32, public: bool, rand_id: &str) -> Self {

@ -69,7 +69,7 @@ impl Network {
poll.registry().register(&mut server, SERVER, Interest::READABLE).expect("Error registering poll");
// Starting peer connections to bootstrap nodes
self.peers.connect_peers(&peers_addrs, &poll.registry(), &mut self.token, yggdrasil_only);
self.peers.connect_peers(&peers_addrs, poll.registry(), &mut self.token, yggdrasil_only);
let mut ui_timer = Instant::now();
let mut log_timer = Instant::now();
@ -83,7 +83,7 @@ impl Network {
if self.peers.get_peers_count() == 0 && bootstrap_timer.elapsed().as_secs() > 60 {
warn!("Restarting swarm connections...");
// Starting peer connections to bootstrap nodes
self.peers.connect_peers(&peers_addrs, &poll.registry(), &mut self.token, yggdrasil_only);
self.peers.connect_peers(&peers_addrs, poll.registry(), &mut self.token, yggdrasil_only);
bootstrap_timer = Instant::now();
last_events_time = Instant::now();
}
@ -102,45 +102,42 @@ impl Network {
//debug!("Event for server socket {} is {:?}", event.token().0, &event);
// If this is an event for the server, it means a connection is ready to be accepted.
let connection = server.accept();
match connection {
Ok((mut stream, mut address)) => {
// Checking if it is an ipv4-mapped ipv6 if yes convert to ipv4
if address.is_ipv6() {
if let IpAddr::V6(ipv6) = address.ip() {
if let Some(ipv4) = ipv6.to_ipv4() {
address = SocketAddr::V4(SocketAddrV4::new(ipv4, address.port()))
}
if let Ok((mut stream, mut address)) = connection {
// Checking if it is an ipv4-mapped ipv6 if yes convert to ipv4
if address.is_ipv6() {
if let IpAddr::V6(ipv6) = address.ip() {
if let Some(ipv4) = ipv6.to_ipv4() {
address = SocketAddr::V4(SocketAddrV4::new(ipv4, address.port()))
}
}
}
if self.peers.is_ignored(&address.ip()) {
debug!("Ignoring connection from banned {:?}", &address.ip());
continue;
}
if yggdrasil_only && !is_yggdrasil(&address.ip()) {
debug!("Dropping connection from Internet");
stream.shutdown(Shutdown::Both).unwrap_or_else(|e| {
warn!("Error in shutdown, {}", e);
});
let _ = poll.registry().reregister(&mut server, SERVER, Interest::READABLE);
continue;
}
if self.peers.is_ignored(&address.ip()) {
debug!("Ignoring connection from banned {:?}", &address.ip());
continue;
}
//debug!("Accepted connection from: {} to local IP: {}", address, local_ip);
let token = self.next_token();
poll.registry().register(&mut stream, token, Interest::READABLE).expect("Error registering poll");
let peer = Peer::new(address, stream, State::Connected, true);
self.peers.add_peer(token, peer);
if yggdrasil_only && !is_yggdrasil(&address.ip()) {
debug!("Dropping connection from Internet");
stream.shutdown(Shutdown::Both).unwrap_or_else(|e| {
warn!("Error in shutdown, {}", e);
});
let _ = poll.registry().reregister(&mut server, SERVER, Interest::READABLE);
continue;
}
Err(_) => {}
//debug!("Accepted connection from: {} to local IP: {}", address, local_ip);
let token = self.next_token();
poll.registry().register(&mut stream, token, Interest::READABLE).expect("Error registering poll");
let peer = Peer::new(address, stream, State::Connected, true);
self.peers.add_peer(token, peer);
}
if let Err(e) = poll.registry().reregister(&mut server, SERVER, Interest::READABLE) {
panic!("Error reregistering server token!\n{}", e);
}
}
token => {
if !self.handle_connection_event(&poll.registry(), &event) {
if !self.handle_connection_event(poll.registry(), event) {
let _ = self.peers.close_peer(poll.registry(), &token);
let blocks = self.context.lock().unwrap().chain.get_height();
let keys = self.context.lock().unwrap().chain.get_users_count();
@ -227,8 +224,8 @@ impl Network {
}
match peer.get_state().clone() {
State::Connected => {
let mut stream = peer.get_stream();
return match read_client_handshake(&mut stream) {
let stream = peer.get_stream();
return match read_client_handshake(stream) {
Ok(key) => {
let mut buf = [0u8; 32];
buf.copy_from_slice(key.as_slice());
@ -251,8 +248,8 @@ impl Network {
};
}
State::ServerHandshake => {
let mut stream = peer.get_stream();
return match read_server_handshake(&mut stream) {
let stream = peer.get_stream();
return match read_server_handshake(stream) {
Ok(data) => {
if data.len() != 32 + 12 {
warn!("Server handshake of {} bytes instead of {}", data.len(), 32 + 12);
@ -278,19 +275,18 @@ impl Network {
};
}
_ => {
let mut stream = peer.get_stream();
read_message(&mut stream)
let stream = peer.get_stream();
read_message(stream)
}
}
}
}
};
if data.is_ok() {
if let Ok(data) = data {
let data = {
match self.peers.get_peer(&event.token()) {
Some(peer) => {
let data = data.unwrap();
match decode_message(&data, peer.get_cipher()) {
Ok(data) => data,
Err(_) => {
@ -344,9 +340,9 @@ impl Network {
}
}
}
Err(_) => {
Err(e) => {
let peer = self.peers.get_peer(&event.token()).unwrap();
warn!("Error deserializing message from {}", &peer.get_addr());
warn!("Error deserializing message from {}: {}", &peer.get_addr(), e.to_string());
return false;
}
}
@ -368,7 +364,7 @@ impl Network {
Some(peer) => {
match peer.get_state().clone() {
State::Connecting => {
if send_client_handshake(&mut peer.get_stream(), self.public_key.as_bytes()).is_err() {
if send_client_handshake(peer.get_stream(), self.public_key.as_bytes()).is_err() {
return false;
}
peer.set_state(State::ServerHandshake);
@ -442,18 +438,16 @@ impl Network {
if self.peers.is_our_own_connect(&rand_id) {
warn!("Detected loop connect");
State::SendLoop
} else if origin.eq(my_origin) && version == my_version {
let peer = self.peers.get_mut_peer(token).unwrap();
peer.set_public(public);
peer.set_active(true);
debug!("Incoming v{} on {}", &app_version, peer.get_addr().ip());
let app_version = self.context.lock().unwrap().app_version.clone();
State::message(Message::shake(&app_version, &origin, version, me_public, &my_id, my_height))
} else {
if origin.eq(my_origin) && version == my_version {
let peer = self.peers.get_mut_peer(token).unwrap();
peer.set_public(public);
peer.set_active(true);
debug!("Incoming v{} on {}", &app_version, peer.get_addr().ip());
let app_version = self.context.lock().unwrap().app_version.clone();
State::message(Message::shake(&app_version, &origin, version, me_public, &my_id, my_height))
} else {
warn!("Handshake from unsupported chain or version");
State::Banned
}
warn!("Handshake from unsupported chain or version");
State::Banned
}
}
Message::Shake { app_version, origin, version, public, rand_id, height } => {
@ -516,20 +510,18 @@ impl Network {
info!("Hashes are different, requesting block {} from {}", my_height, peer.get_addr().ip());
info!("My hash: {:?}, their hash: {:?}", &my_hash, &hash);
State::message(Message::GetBlock { index: my_height })
} else if active_count < MAX_NODES && random::<u8>() < 50 {
debug!("Requesting more peers from {}", peer.get_addr().ip());
State::message(Message::GetPeers)
} else {
if active_count < MAX_NODES && random::<u8>() < 50 {
debug!("Requesting more peers from {}", peer.get_addr().ip());
State::message(Message::GetPeers)
} else {
State::idle()
}
State::idle()
}
}
Message::GetPeers => {
let addr = {
let peer = self.peers.get_mut_peer(token).unwrap();
peer.set_active(true);
peer.get_addr().clone()
peer.get_addr()
};
State::message(Message::Peers { peers: self.peers.get_peers_for_exchange(&addr) })
}
@ -584,7 +576,7 @@ impl Network {
// If we have some consequent blocks in a bucket of 'future blocks', we add them
while let Some(block) = self.future_blocks.remove(&next_index) {
if context.chain.check_new_block(&block) == BlockQuality::Good {
info!("Added block {} from future blocks", next_index);
debug!("Added block {} from future blocks", next_index);
context.chain.add_block(block);
} else {
warn!("Block {} in future blocks is bad!", block.index);
@ -656,21 +648,18 @@ impl Network {
fn subscribe_to_bus(running: Arc<AtomicBool>) {
use crate::event::Event;
register(move |_uuid, e| {
match e {
Event::ActionQuit => {
running.store(false, Ordering::SeqCst);
return false;
}
_ => {}
if let Event::ActionQuit = e {
running.store(false, Ordering::SeqCst);
return false;
}
true
});
}
fn encode_bytes(data: &Vec<u8>, cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> {
fn encode_bytes(data: &[u8], cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> {
match cipher {
None => Ok(data.clone()),
Some(chacha) => chacha.encrypt(data.as_slice())
None => Ok(data.to_owned()),
Some(chacha) => chacha.encrypt(data)
}
}
@ -695,10 +684,10 @@ fn encode_message(message: &Message, cipher: &Option<Chacha>) -> Result<Vec<u8>,
}
}
fn decode_message(data: &Vec<u8>, cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> {
fn decode_message(data: &[u8], cipher: &Option<Chacha>) -> Result<Vec<u8>, chacha20poly1305::aead::Error> {
match cipher {
None => Ok(data.clone()),
Some(chacha) => chacha.decrypt(data.as_slice())
None => Ok(data.to_owned()),
Some(chacha) => chacha.decrypt(data)
}
}
@ -804,13 +793,13 @@ fn read_server_handshake(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
}
}
fn send_message(connection: &mut TcpStream, data: &Vec<u8>) -> io::Result<()> {
fn send_message(connection: &mut TcpStream, data: &[u8]) -> io::Result<()> {
let data_len = data.len() as u16;
//debug!("Sending {} bytes", data_len);
//debug!("Message: {:?}", to_hex(&data));
let mut buf: Vec<u8> = Vec::with_capacity(data.len() + 2);
buf.write_u16::<BigEndian>(data_len ^ 0xAAAA)?;
buf.write_all(&data)?;
buf.write_all(data)?;
connection.write_all(&buf)?;
connection.flush()
}

@ -57,7 +57,7 @@ impl Peer {
}
pub fn get_addr(&self) -> SocketAddr {
self.addr.clone()
self.addr
}
pub fn get_stream(&mut self) -> &mut TcpStream {

@ -53,51 +53,48 @@ impl Peers {
pub fn close_peer(&mut self, registry: &Registry, token: &Token) {
let peer = self.peers.get_mut(token);
match peer {
Some(peer) => {
let stream = peer.get_stream();
let _ = stream.shutdown(Shutdown::Both);
let _ = registry.deregister(stream);
match peer.get_state() {
State::Connecting => {
debug!("Peer connection {} to {:?} has timed out", &token.0, &peer.get_addr());
}
State::Connected => {
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
}
State::Idle { .. } | State::Message { .. } => {
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
}
State::Error => {
debug!("Peer connection {} to {:?} has shut down on error", &token.0, &peer.get_addr());
}
State::Banned => {
debug!("Peer connection {} to {:?} has shut down, banned", &token.0, &peer.get_addr());
self.ignored.insert(peer.get_addr().ip().clone());
}
State::Offline { .. } => {
debug!("Peer connection {} to {:?} is offline", &token.0, &peer.get_addr());
}
State::SendLoop => {
debug!("Peer connection {} from {:?} is a loop", &token.0, &peer.get_addr());
}
State::Loop => {
debug!("Peer connection {} to {:?} is a loop", &token.0, &peer.get_addr());
}
State::Twin => {
debug!("Peer connection {} to {:?} is a twin", &token.0, &peer.get_addr());
}
State::ServerHandshake => {
debug!("Peer connection {} from {:?} didn't shake hands", &token.0, &peer.get_addr());
}
State::HandshakeFinished => {
debug!("Peer connection {} from {:?} shook hands, but then failed", &token.0, &peer.get_addr());
}
if let Some(peer) = peer {
let stream = peer.get_stream();
let _ = stream.shutdown(Shutdown::Both);
let _ = registry.deregister(stream);
match peer.get_state() {
State::Connecting => {
debug!("Peer connection {} to {:?} has timed out", &token.0, &peer.get_addr());
}
State::Connected => {
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
}
State::Idle { .. } | State::Message { .. } => {
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
}
State::Error => {
debug!("Peer connection {} to {:?} has shut down on error", &token.0, &peer.get_addr());
}
State::Banned => {
debug!("Peer connection {} to {:?} has shut down, banned", &token.0, &peer.get_addr());
self.ignored.insert(peer.get_addr().ip());
}
State::Offline { .. } => {
debug!("Peer connection {} to {:?} is offline", &token.0, &peer.get_addr());
}
State::SendLoop => {
debug!("Peer connection {} from {:?} is a loop", &token.0, &peer.get_addr());
}
State::Loop => {
debug!("Peer connection {} to {:?} is a loop", &token.0, &peer.get_addr());
}
State::Twin => {
debug!("Peer connection {} to {:?} is a twin", &token.0, &peer.get_addr());
}
State::ServerHandshake => {
debug!("Peer connection {} from {:?} didn't shake hands", &token.0, &peer.get_addr());
}
State::HandshakeFinished => {
debug!("Peer connection {} from {:?} shook hands, but then failed", &token.0, &peer.get_addr());
}
self.peers.remove(token);
}
None => {}
self.peers.remove(token);
}
}
@ -129,16 +126,14 @@ impl Peers {
if self.peers
.iter()
.find(|(_token, peer)| peer.get_addr().ip() == addr.ip())
.is_some() {
.any(|(_token, peer)| peer.get_addr().ip() == addr.ip()) {
//debug!("Skipping address from exchange: {}", &addr);
continue;
}
if self.new_peers
.iter()
.find(|a| a.ip().eq(&addr.ip()))
.is_some() {
.any(|a| a.ip().eq(&addr.ip())) {
//debug!("Skipping address from exchange: {}", &addr);
continue;
}
@ -223,13 +218,13 @@ impl Peers {
if !peer.get_state().is_loop() {
peer.set_state(State::Banned);
}
let ip = peer.get_addr().ip().clone();
let ip = peer.get_addr().ip();
self.close_peer(registry, token);
self.ignored.insert(ip);
match self.peers
.iter()
.find(|(_, p)| p.get_addr().ip() == ip)
.map(|(t, _)| t.clone()) {
.map(|(t, _)| *t) {
None => {}
Some(t) => {
self.close_peer(registry, &t);
@ -240,7 +235,7 @@ impl Peers {
pub fn ignore_ip(&mut self, ip: &IpAddr) {
info!("Adding {} to ignored peers", &ip);
self.ignored.insert(ip.clone());
self.ignored.insert(*ip);
}
pub fn skip_peer_connection(&self, addr: &SocketAddr) -> bool {
@ -257,22 +252,19 @@ impl Peers {
let random_time = random::<u64>() % PING_PERIOD;
for (token, peer) in self.peers.iter_mut() {
match peer.get_state() {
State::Idle { from } => {
if from.elapsed().as_secs() >= PING_PERIOD + random_time {
// Sometimes we check for new peers instead of pinging
let message = if nodes < MAX_NODES && random::<bool>() {
Message::GetPeers
} else {
Message::ping(height, hash.clone())
};
peer.set_state(State::message(message));
let stream = peer.get_stream();
registry.reregister(stream, token.clone(), Interest::WRITABLE).unwrap();
}
if let State::Idle { from } = peer.get_state() {
if from.elapsed().as_secs() >= PING_PERIOD + random_time {
// Sometimes we check for new peers instead of pinging
let message = if nodes < MAX_NODES && random::<bool>() {
Message::GetPeers
} else {
Message::ping(height, hash.clone())
};
peer.set_state(State::message(message));
let stream = peer.get_stream();
registry.reregister(stream, *token, Interest::WRITABLE).unwrap();
}
_ => {}
}
}
@ -283,11 +275,9 @@ impl Peers {
}
// If someone has more blocks we sync
if nodes >= MIN_CONNECTED_NODES_START_SYNC {
if height < max_height {
let count = min(max_height - height, nodes as u64);
self.ask_blocks_from_peers(registry, height, height + count, have_blocks);
}
if nodes >= MIN_CONNECTED_NODES_START_SYNC && height < max_height {
let count = min(max_height - height, nodes as u64);
self.ask_blocks_from_peers(registry, height, height + count, have_blocks);
}
// If someone has less blocks (we mined a new block) we send a ping with our height
@ -300,7 +290,7 @@ impl Peers {
None => {}
Some((token, peer)) => {
debug!("Peer {} is behind, sending ping", &peer.get_addr().ip());
registry.reregister(peer.get_stream(), token.clone(), Interest::WRITABLE).unwrap();
registry.reregister(peer.get_stream(), *token, Interest::WRITABLE).unwrap();
peer.set_state(State::message(Message::Ping { height, hash }));
self.update_behind_ping_time();
}
@ -323,9 +313,9 @@ impl Peers {
for (token, peer) in self.peers.iter_mut() {
if peer.get_state().need_reconnect() {
let addr = peer.get_addr();
if let Ok(mut stream) = TcpStream::connect(addr.clone()) {
if let Ok(mut stream) = TcpStream::connect(addr) {
debug!("Trying to reconnect to peer {}, count {}", &addr, peer.reconnects());
registry.register(&mut stream, token.clone(), Interest::WRITABLE).unwrap();
registry.register(&mut stream, *token, Interest::WRITABLE).unwrap();
peer.set_state(State::Connecting);
peer.inc_reconnects();
peer.set_stream(stream);
@ -346,7 +336,7 @@ impl Peers {
None => {}
Some((token, peer)) => {
debug!("Peer {} is higher than we are, requesting block {}", &peer.get_addr().ip(), height + 1);
registry.reregister(peer.get_stream(), token.clone(), Interest::WRITABLE).unwrap();
registry.reregister(peer.get_stream(), *token, Interest::WRITABLE).unwrap();
peer.set_state(State::message(Message::GetBlock { index: height + 1 }));
}
}
@ -366,7 +356,7 @@ impl Peers {
continue;
}
debug!("Peer {} is higher than we are, requesting block {}", &peer.get_addr().ip(), index);
registry.reregister(peer.get_stream(), token.clone(), Interest::WRITABLE).unwrap();
registry.reregister(peer.get_stream(), *token, Interest::WRITABLE).unwrap();
peer.set_state(State::message(Message::GetBlock { index }));
index += 1;
if index > max_height {
@ -390,7 +380,7 @@ impl Peers {
}
/// Connecting to configured (bootstrap) peers
pub fn connect_peers(&mut self, peers_addrs: &Vec<String>, registry: &Registry, unique_token: &mut Token, yggdrasil_only: bool) {
pub fn connect_peers(&mut self, peers_addrs: &[String], registry: &Registry, unique_token: &mut Token, yggdrasil_only: bool) {
let mut set = HashSet::new();
for peer in peers_addrs.iter() {
info!("Resolving address {}", peer);
@ -405,7 +395,7 @@ impl Peers {
break;
}
while addresses.len() > 0 {
while !addresses.is_empty() {
let addr = addresses.remove(0);
if !set.contains(&addr) {
match self.connect_peer(&addr, registry, unique_token, yggdrasil_only) {
@ -420,7 +410,7 @@ impl Peers {
}
// Copy others to new_peers, to connect later
if addresses.len() > 0 {
if !addresses.is_empty() {
self.new_peers.append(&mut addresses);
}
}
@ -435,13 +425,13 @@ impl Peers {
return Err(io::Error::from(io::ErrorKind::InvalidInput));
}
trace!("Connecting to peer {}", &addr);
match TcpStream::connect(addr.clone()) {
match TcpStream::connect(*addr) {
Ok(mut stream) => {
//stream.set_nodelay(true)?;
let token = next(unique_token);
trace!("Created connection {}, to peer {}", &token.0, &addr);
registry.register(&mut stream, token, Interest::WRITABLE).unwrap();
let mut peer = Peer::new(addr.clone(), stream, State::Connecting, false);
let mut peer = Peer::new(*addr, stream, State::Connecting, false);
peer.set_public(true);
self.peers.insert(token, peer);
Ok(())
@ -459,6 +449,12 @@ impl Peers {
}
}
impl Default for Peers {
fn default() -> Self {
Self::new()
}
}
/// Gets new token from old token, mutating the last
pub fn next(current: &mut Token) -> Token {
let next = current.0;

@ -33,18 +33,11 @@ impl State {
}
pub fn is_idle(&self) -> bool {
match self {
State::Idle { .. } => true,
_ => false
}
matches!(self, State::Idle { .. })
}
pub fn is_loop(&self) -> bool {
match self {
State::Loop { .. } => true,
State::SendLoop { .. } => true,
_ => false
}
matches!(self, State::Loop { .. } | State::SendLoop { .. })
}
pub fn disabled(&self) -> bool {

@ -126,7 +126,7 @@ fn action_check_domain(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>
let c = context.lock().unwrap();
if let Some(keystore) = c.get_keystore() {
let name = name.to_lowercase();
let available = c.get_chain().is_domain_available(c.get_chain().get_height(), &name, &keystore);
let available = c.get_chain().is_domain_available(c.get_chain().get_height(), &name, keystore);
web_view.eval(&format!("domainAvailable({})", available)).expect("Error evaluating!");
}
}
@ -207,7 +207,7 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
_ => threads
};
let status = Arc::new(Mutex::new(UiStatus::new(threads)));
let context_copy = Arc::clone(&context);
let context_copy = Arc::clone(context);
let c = context.lock().unwrap();
register(move |_uuid, e| {
@ -221,7 +221,7 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
let eval = match e {
Event::KeyCreated { path, public, hash } => {
load_domains(&mut context, &handle);
send_keys_to_ui(&mut context, &handle);
send_keys_to_ui(&context, &handle);
event_handle_luck(&handle, "Key successfully created! Don\\'t forget to save it!");
let mut s = format!("keystoreChanged('{}', '{}', '{}');", &path, &public, &hash);
s.push_str(" showSuccess('New key mined successfully! Save it to a safe place!')");
@ -230,7 +230,7 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
Event::KeyLoaded { path, public, hash } |
Event::KeySaved { path, public, hash } => {
load_domains(&mut context, &handle);
send_keys_to_ui(&mut context, &handle);
send_keys_to_ui(&context, &handle);
format!("keystoreChanged('{}', '{}', '{}');", &path, &public, &hash)
}
Event::MinerStarted | Event::KeyGeneratorStarted => {
@ -301,7 +301,7 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
if status.mining {
String::from("setLeftStatusBarText('Mining...'); showMiningIndicator(true, false);")
} else {
format!("setLeftStatusBarText('Idle'); showMiningIndicator(false, false);")
String::from("setLeftStatusBarText('Idle'); showMiningIndicator(false, false);")
}
}
Event::NetworkStatus { blocks, domains, keys, nodes } => {
@ -376,7 +376,7 @@ fn send_keys_to_ui(context: &MutexGuard<Context>, handle: &Handle<()>) {
let mut keys = Vec::new();
for key in context.get_keystores() {
let path = key.get_path().replace("\\", "/");
let parts: Vec<&str> = path.rsplitn(2, "/").collect();
let parts: Vec<&str> = path.rsplitn(2, '/').collect();
keys.push(KeysForJS { file_name: parts[0].to_owned(), public: key.get_public().to_string() });
}
keys
@ -425,14 +425,12 @@ fn action_create_domain(context: Arc<Mutex<Context>>, miner: Arc<Mutex<Miner>>,
// Check if yggdrasil only quality of zone is not violated
let zones = context.chain.get_zones();
for z in zones {
if z.name == data.zone {
if z.yggdrasil {
for record in &data.records {
if !is_yggdrasil_record(record) {
show_warning(web_view, &format!("Zone {} is Yggdrasil only, you cannot use IPs from clearnet!", &data.zone));
let _ = web_view.eval("domainMiningUnavailable();");
return;
}
if z.name == data.zone && z.yggdrasil {
for record in &data.records {
if !is_yggdrasil_record(record) {
show_warning(web_view, &format!("Zone {} is Yggdrasil only, you cannot use IPs from clearnet!", &data.zone));
let _ = web_view.eval("domainMiningUnavailable();");
return;
}
}
}
@ -562,6 +560,7 @@ fn format_event_now(kind: &str, message: &str) -> String {
format!("addEvent('{}', '{}', '{}');", kind, time.format("%d.%m.%y %X"), message)
}
#[allow(clippy::too_many_arguments)]
fn create_domain(context: Arc<Mutex<Context>>, miner: Arc<Mutex<Miner>>, class: &str, name: &str, mut data: DomainData, difficulty: u32, keystore: &Keystore, signing: Bytes, encryption: Bytes) {
let name = name.to_owned();
let encrypted = CryptoBox::encrypt(encryption.as_slice(), name.as_bytes()).expect("Error encrypting domain name!");
@ -613,8 +612,7 @@ struct UiStatus {
impl UiStatus {
fn new(threads: usize) -> Self {
let mut speed = Vec::with_capacity(threads);
speed.resize(threads, 0u64);
let speed =vec![0; threads];
UiStatus { mining: false, syncing: false, synced_blocks: 0, sync_height: 0, max_diff: 0, speed }
}

Loading…
Cancel
Save