Fixed multiple clippy warnings.
This commit is contained in:
@@ -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 {
|
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 {
|
Block {
|
||||||
index,
|
index,
|
||||||
|
|||||||
+30
-34
@@ -81,6 +81,7 @@ impl Chain {
|
|||||||
if !self.origin.is_zero() && !options.origin.is_empty() && self.origin.to_string() != options.origin {
|
if !self.origin.is_zero() && !options.origin.is_empty() && self.origin.to_string() != options.origin {
|
||||||
self.clear_db();
|
self.clear_db();
|
||||||
}
|
}
|
||||||
|
#[allow(clippy::absurd_extreme_comparisons)]
|
||||||
if options.version < DB_VERSION {
|
if options.version < DB_VERSION {
|
||||||
self.migrate_db(options.version, DB_VERSION);
|
self.migrate_db(options.version, DB_VERSION);
|
||||||
}
|
}
|
||||||
@@ -278,7 +279,7 @@ impl Chain {
|
|||||||
Ok(())
|
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 {
|
if self.get_height() < BLOCK_SIGNERS_START {
|
||||||
trace!("Too early to start block signings");
|
trace!("Too early to start block signings");
|
||||||
return None;
|
return None;
|
||||||
@@ -419,7 +420,7 @@ impl Chain {
|
|||||||
match self.db.prepare(SQL_GET_BLOCK_BY_ID) {
|
match self.db.prepare(SQL_GET_BLOCK_BY_ID) {
|
||||||
Ok(mut statement) => {
|
Ok(mut statement) => {
|
||||||
statement.bind(1, index as i64).expect("Error in bind");
|
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) {
|
return match Self::get_block_from_statement(&mut statement) {
|
||||||
None => {
|
None => {
|
||||||
error!("Something wrong with block in DB!");
|
error!("Something wrong with block in DB!");
|
||||||
@@ -470,7 +471,7 @@ impl Chain {
|
|||||||
statement
|
statement
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
while statement.next().unwrap() == State::Row {
|
if statement.next().unwrap() == State::Row {
|
||||||
return match Self::get_block_from_statement(&mut statement) {
|
return match Self::get_block_from_statement(&mut statement) {
|
||||||
None => {
|
None => {
|
||||||
error!("Something wrong with block in DB!");
|
error!("Something wrong with block in DB!");
|
||||||
@@ -495,10 +496,10 @@ impl Chain {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
let parts: Vec<&str> = domain.rsplitn(2, ".").collect();
|
let parts: Vec<&str> = domain.rsplitn(2, '.').collect();
|
||||||
if parts.len() > 1 {
|
if parts.len() > 1 {
|
||||||
// We do not support third level domains
|
// We do not support third level domains
|
||||||
if parts.last().unwrap().contains(".") {
|
if parts.last().unwrap().contains('.') {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return self.is_available_zone(parts.first().unwrap());
|
return self.is_available_zone(parts.first().unwrap());
|
||||||
@@ -527,7 +528,7 @@ impl Chain {
|
|||||||
fn load_zones() -> Vec<ZoneData> {
|
fn load_zones() -> Vec<ZoneData> {
|
||||||
let mut result: Vec<ZoneData> = Vec::new();
|
let mut result: Vec<ZoneData> = Vec::new();
|
||||||
let zones_text = ZONES_TXT.replace("\r", "");
|
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 {
|
for zone in zones {
|
||||||
let yggdrasil = zone == "ygg" || zone == "anon";
|
let yggdrasil = zone == "ygg" || zone == "anon";
|
||||||
result.push(ZoneData { name: zone.to_owned(), yggdrasil })
|
result.push(ZoneData { name: zone.to_owned(), yggdrasil })
|
||||||
@@ -536,7 +537,7 @@ impl Chain {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_zones_hash() -> Bytes {
|
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
|
/// 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();
|
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(1, height as i64).expect("Error in bind");
|
||||||
statement.bind(2, &***id).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
|
// If there is such a zone
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -579,7 +580,7 @@ impl Chain {
|
|||||||
}
|
}
|
||||||
let identity_hash = hash_identity(&name, None);
|
let identity_hash = hash_identity(&name, None);
|
||||||
// TODO extract method
|
// 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 new_id = !self.is_domain_in_blockchain(height, &identity_hash);
|
||||||
let time = last.timestamp + NEW_DOMAINS_INTERVAL - Utc::now().timestamp();
|
let time = last.timestamp + NEW_DOMAINS_INTERVAL - Utc::now().timestamp();
|
||||||
if new_id && time > 0 {
|
if new_id && time > 0 {
|
||||||
@@ -593,7 +594,7 @@ impl Chain {
|
|||||||
pub fn get_id_transaction(&self, identity_hash: &Bytes) -> Option<Transaction> {
|
pub fn get_id_transaction(&self, identity_hash: &Bytes) -> Option<Transaction> {
|
||||||
let mut statement = self.db.prepare(SQL_GET_DOMAIN_BY_ID).unwrap();
|
let mut statement = self.db.prepare(SQL_GET_DOMAIN_BY_ID).unwrap();
|
||||||
statement.bind(1, identity_hash.as_slice()).expect("Error in bind");
|
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();
|
let timestamp = statement.read::<i64>(1).unwrap();
|
||||||
if timestamp < Utc::now().timestamp() - DOMAIN_LIFETIME {
|
if timestamp < Utc::now().timestamp() - DOMAIN_LIFETIME {
|
||||||
// This domain is too old
|
// This domain is too old
|
||||||
@@ -635,7 +636,7 @@ impl Chain {
|
|||||||
|
|
||||||
pub fn get_domains_count(&self) -> i64 {
|
pub fn get_domains_count(&self) -> i64 {
|
||||||
let mut statement = self.db.prepare(SQL_GET_DOMAINS_COUNT).unwrap();
|
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();
|
return statement.read::<i64>(0).unwrap();
|
||||||
}
|
}
|
||||||
0
|
0
|
||||||
@@ -643,7 +644,7 @@ impl Chain {
|
|||||||
|
|
||||||
pub fn get_users_count(&self) -> i64 {
|
pub fn get_users_count(&self) -> i64 {
|
||||||
let mut statement = self.db.prepare(SQL_GET_USERS_COUNT).unwrap();
|
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();
|
return statement.read::<i64>(0).unwrap();
|
||||||
}
|
}
|
||||||
0
|
0
|
||||||
@@ -665,7 +666,7 @@ impl Chain {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut result = HashMap::new();
|
let mut result = HashMap::new();
|
||||||
let keystore = keystore.clone().unwrap();
|
let keystore = keystore.unwrap();
|
||||||
let pub_key = keystore.get_public();
|
let pub_key = keystore.get_public();
|
||||||
let mut statement = self.db.prepare(SQL_GET_DOMAINS_BY_KEY).unwrap();
|
let mut statement = self.db.prepare(SQL_GET_DOMAINS_BY_KEY).unwrap();
|
||||||
statement.bind(1, &**pub_key).expect("Error in bind");
|
statement.bind(1, &**pub_key).expect("Error in bind");
|
||||||
@@ -785,7 +786,7 @@ impl Chain {
|
|||||||
SIGNER_DIFFICULTY
|
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 {
|
if block.difficulty < difficulty {
|
||||||
warn!("Block difficulty is lower than needed");
|
warn!("Block difficulty is lower than needed");
|
||||||
@@ -799,7 +800,7 @@ impl Chain {
|
|||||||
warn!("Ignoring block with wrong hash:\n{:?}", &block);
|
warn!("Ignoring block with wrong hash:\n{:?}", &block);
|
||||||
return Bad;
|
return Bad;
|
||||||
}
|
}
|
||||||
if !check_block_signature(&block) {
|
if !check_block_signature(block) {
|
||||||
warn!("Ignoring block with wrong signature:\n{:?}", &block);
|
warn!("Ignoring block with wrong signature:\n{:?}", &block);
|
||||||
return Bad;
|
return Bad;
|
||||||
}
|
}
|
||||||
@@ -843,19 +844,17 @@ impl Chain {
|
|||||||
}
|
}
|
||||||
let zones = self.get_zones();
|
let zones = self.get_zones();
|
||||||
for z in zones {
|
for z in zones {
|
||||||
if z.name == block_data.zone {
|
if z.name == block_data.zone && z.yggdrasil {
|
||||||
if z.yggdrasil {
|
for record in &block_data.records {
|
||||||
for record in &block_data.records {
|
if !is_yggdrasil_record(record) {
|
||||||
if !is_yggdrasil_record(record) {
|
warn!("Someone mined domain with clearnet records for Yggdrasil only zone!");
|
||||||
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;
|
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 block.index > BLOCK_SIGNERS_START {
|
||||||
// If this block is main, signed part of blockchain
|
// 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;
|
return Bad;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -926,15 +925,12 @@ impl Chain {
|
|||||||
if block.index > full_block.index && block.transaction.is_some() {
|
if block.index > full_block.index && block.transaction.is_some() {
|
||||||
warn!("Not enough signing blocks over full {} block!", full_block.index);
|
warn!("Not enough signing blocks over full {} block!", full_block.index);
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else if !self.is_good_signer_for_block(block, full_block) {
|
||||||
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) {
|
|
||||||
return false;
|
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
|
true
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ impl DnsFilter for BlockchainFilter {
|
|||||||
fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
|
fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
|
||||||
let search;
|
let search;
|
||||||
let subdomain;
|
let subdomain;
|
||||||
let parts: Vec<&str> = qname.rsplitn(3, ".").collect();
|
let parts: Vec<&str> = qname.rsplitn(3, '.').collect();
|
||||||
match parts.len() {
|
match parts.len() {
|
||||||
1 => {
|
1 => {
|
||||||
let mut packet = DnsPacket::new();
|
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);
|
let have_zone = self.context.lock().unwrap().chain.is_available_zone(zone);
|
||||||
if have_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
|
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.
|
/// 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)
|
/// 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 {
|
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);
|
let identity = hash_sha256(&base);
|
||||||
match key {
|
match key {
|
||||||
None => Bytes::from_bytes(&identity),
|
None => Bytes::from_bytes(&identity),
|
||||||
Some(key) => {
|
Some(key) => {
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
buf.append(&mut base.clone());
|
buf.append(&mut base);
|
||||||
buf.append(&mut key.to_vec());
|
buf.append(&mut key.to_vec());
|
||||||
Bytes::from_bytes(&hash_sha256(&buf))
|
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 {
|
pub fn from_str(identity: String, method: String, data: String, signing: Bytes, encryption: Bytes) -> Self {
|
||||||
let hash = hash_identity(&identity, None);
|
let hash = hash_identity(&identity, None);
|
||||||
let confirmation = hash_identity(&identity, Some(&signing));
|
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 {
|
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 {
|
pub fn to_string(&self) -> String {
|
||||||
// Let it panic if something is not okay
|
// Let it panic if something is not okay
|
||||||
serde_json::to_string(&self).unwrap()
|
serde_json::to_string(&self).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_identity(&self, domain: &str) -> bool {
|
pub fn check_identity(&self, domain: &str) -> bool {
|
||||||
let hash = hash_identity(&domain, None);
|
let hash = hash_identity(domain, None);
|
||||||
let confirmation = hash_identity(&domain, Some(&self.signing));
|
let confirmation = hash_identity(domain, Some(&self.signing));
|
||||||
self.identity.eq(&hash) && self.confirmation.eq(&confirmation)
|
self.identity.eq(&hash) && self.confirmation.eq(&confirmation)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+8
-17
@@ -13,7 +13,7 @@ use num_bigint::BigUint;
|
|||||||
use serde::de::{Error as DeError, Visitor};
|
use serde::de::{Error as DeError, Visitor};
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Default)]
|
||||||
pub struct Bytes {
|
pub struct Bytes {
|
||||||
data: Vec<u8>
|
data: Vec<u8>
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,7 @@ impl Bytes {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a byte slice of the hash contents.
|
/// Returns a byte slice of the hash contents.
|
||||||
@@ -57,6 +57,7 @@ impl Bytes {
|
|||||||
self.data.as_mut_slice()
|
self.data.as_mut_slice()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::inherent_to_string)]
|
||||||
pub fn to_string(&self) -> String {
|
pub fn to_string(&self) -> String {
|
||||||
crate::commons::to_hex(&self.data)
|
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 {
|
impl PartialEq for Bytes {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
crate::blockchain::hash_utils::same_hash(&self, &other)
|
crate::blockchain::hash_utils::same_hash(self, other)
|
||||||
}
|
|
||||||
|
|
||||||
fn ne(&self, other: &Self) -> bool {
|
|
||||||
!crate::blockchain::hash_utils::same_hash(&self, &other)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,16 +87,16 @@ impl Eq for Bytes {}
|
|||||||
|
|
||||||
impl PartialOrd for Bytes {
|
impl PartialOrd for Bytes {
|
||||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||||
let self_hash_int = BigUint::from_bytes_le(&self);
|
let self_hash_int = BigUint::from_bytes_le(self);
|
||||||
let other_hash_int = BigUint::from_bytes_le(&other);
|
let other_hash_int = BigUint::from_bytes_le(other);
|
||||||
Some(self_hash_int.cmp(&other_hash_int))
|
Some(self_hash_int.cmp(&other_hash_int))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Ord for Bytes {
|
impl Ord for Bytes {
|
||||||
fn cmp(&self, other: &Self) -> Ordering {
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
let self_hash_int = BigUint::from_bytes_le(&self);
|
let self_hash_int = BigUint::from_bytes_le(self);
|
||||||
let other_hash_int = BigUint::from_bytes_le(&other);
|
let other_hash_int = BigUint::from_bytes_le(other);
|
||||||
self_hash_int.cmp(&other_hash_int)
|
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;
|
pub const LIMITED_CONFIDENCE_DEPTH: u64 = 4;
|
||||||
|
|
||||||
/// We start mining signing blocks after random delay, this is the max delay
|
/// 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 NEW_DOMAINS_INTERVAL: i64 = 86400; // One day in seconds
|
||||||
pub const DOMAIN_LIFETIME: i64 = 86400 * 365; // One year
|
pub const DOMAIN_LIFETIME: i64 = 86400 * 365; // One year
|
||||||
|
|||||||
+5
-7
@@ -22,7 +22,7 @@ pub fn to_hex(buf: &[u8]) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_hex(string: &str) -> Result<Vec<u8>, num::ParseIntError> {
|
pub fn from_hex(string: &str) -> Result<Vec<u8>, num::ParseIntError> {
|
||||||
split_n(&string.trim()[..], 2)
|
split_n(string.trim(), 2)
|
||||||
.iter()
|
.iter()
|
||||||
.map(|b| u8::from_str_radix(b, 16))
|
.map(|b| u8::from_str_radix(b, 16))
|
||||||
.collect()
|
.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('-') {
|
if name.starts_with('.') || name.starts_with('-') || name.ends_with('.') || name.ends_with('-') {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let parts: Vec<&str> = name.rsplitn(2, ".").collect();
|
let parts: Vec<&str> = name.rsplitn(2, '.').collect();
|
||||||
if parts.len() == 2 {
|
if parts.len() == 2 && parts[1].len() < 3 && is_numeric(parts[1]) {
|
||||||
if parts[1].len() < 3 && is_numeric(parts[1]) {
|
return false;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut last_dot = 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 {
|
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() {
|
if !parts.is_empty() {
|
||||||
parts[0].to_owned()
|
parts[0].to_owned()
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
pub struct Bus<T> {
|
pub struct Bus<T> {
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
listeners: HashMap<Uuid, Box<dyn FnMut(&Uuid, T) -> bool + Send + Sync>>
|
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 {
|
pub fn register<F>(&mut self, closure: F) -> Uuid where F: FnMut(&Uuid, T) -> bool + Send + Sync + 'static {
|
||||||
let uuid = Uuid::new_v4();
|
let uuid = Uuid::new_v4();
|
||||||
self.listeners.insert(uuid.clone(), Box::new(closure));
|
self.listeners.insert(uuid, Box::new(closure));
|
||||||
uuid
|
uuid
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn unregister(&mut self, uuid: &Uuid) {
|
pub fn unregister(&mut self, uuid: &Uuid) {
|
||||||
self.listeners.remove(&uuid);
|
self.listeners.remove(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn post(&mut self, event: T) {
|
pub fn post(&mut self, event: T) {
|
||||||
|
|||||||
@@ -23,12 +23,12 @@ impl Chacha {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
|
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())
|
self.cipher.encrypt(&nonce, data.as_ref())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
|
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())
|
self.cipher.decrypt(&nonce, data.as_ref())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ impl CryptoBox {
|
|||||||
|
|
||||||
pub fn decrypt(secret: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
|
pub fn decrypt(secret: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
|
||||||
let secret = SecretKey::from_bytes(secret).unwrap();
|
let secret = SecretKey::from_bytes(secret).unwrap();
|
||||||
decrypt(&secret, &message)
|
decrypt(&secret, message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,9 +39,9 @@ pub struct Zone {
|
|||||||
impl Zone {
|
impl Zone {
|
||||||
pub fn new(domain: String, m_name: String, r_name: String) -> Zone {
|
pub fn new(domain: String, m_name: String, r_name: String) -> Zone {
|
||||||
Zone {
|
Zone {
|
||||||
domain: domain,
|
domain,
|
||||||
m_name: m_name,
|
m_name,
|
||||||
r_name: r_name,
|
r_name,
|
||||||
serial: 0,
|
serial: 0,
|
||||||
refresh: 0,
|
refresh: 0,
|
||||||
retry: 0,
|
retry: 0,
|
||||||
@@ -222,7 +222,7 @@ impl Authority {
|
|||||||
None => continue
|
None => continue
|
||||||
};
|
};
|
||||||
|
|
||||||
if &domain != qname {
|
if domain != qname {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
-5
@@ -49,7 +49,7 @@ pub trait PacketBuffer {
|
|||||||
self.write(((val >> 24) & 0xFF) as u8)?;
|
self.write(((val >> 24) & 0xFF) as u8)?;
|
||||||
self.write(((val >> 16) & 0xFF) as u8)?;
|
self.write(((val >> 16) & 0xFF) as u8)?;
|
||||||
self.write(((val >> 8) & 0xFF) as u8)?;
|
self.write(((val >> 8) & 0xFF) as u8)?;
|
||||||
self.write(((val >> 0) & 0xFF) as u8)?;
|
self.write((val & 0xFF) as u8)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -95,7 +95,7 @@ pub trait PacketBuffer {
|
|||||||
let res = ((self.read()? as u32) << 24)
|
let res = ((self.read()? as u32) << 24)
|
||||||
| ((self.read()? as u32) << 16)
|
| ((self.read()? as u32) << 16)
|
||||||
| ((self.read()? as u32) << 8)
|
| ((self.read()? as u32) << 8)
|
||||||
| ((self.read()? as u32) << 0);
|
| (self.read()? as u32);
|
||||||
|
|
||||||
Ok(res)
|
Ok(res)
|
||||||
}
|
}
|
||||||
@@ -239,7 +239,7 @@ impl<'a, T> PacketBuffer for StreamPacketBuffer<'a, T> where T: Read + 'a {
|
|||||||
fn read(&mut self) -> Result<u8> {
|
fn read(&mut self) -> Result<u8> {
|
||||||
while self.pos >= self.buffer.len() {
|
while self.pos >= self.buffer.len() {
|
||||||
let mut local_buffer = [0; 1];
|
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]);
|
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> {
|
fn get(&mut self, pos: usize) -> Result<u8> {
|
||||||
while pos >= self.buffer.len() {
|
while pos >= self.buffer.len() {
|
||||||
let mut local_buffer = [0; 1];
|
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]);
|
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]> {
|
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
|
||||||
while start + len > self.buffer.len() {
|
while start + len > self.buffer.len() {
|
||||||
let mut local_buffer = [0; 1];
|
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]);
|
self.buffer.push(local_buffer[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+8
-10
@@ -131,7 +131,7 @@ impl DnsNetworkClient {
|
|||||||
let mut socket = TcpStream::connect(server)?;
|
let mut socket = TcpStream::connect(server)?;
|
||||||
|
|
||||||
write_packet_length(&mut socket, req_buffer.pos())?;
|
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()?;
|
socket.flush()?;
|
||||||
|
|
||||||
let _ = read_packet_length(&mut socket)?;
|
let _ = read_packet_length(&mut socket)?;
|
||||||
@@ -409,7 +409,7 @@ impl HttpsDnsClient {
|
|||||||
.max_idle_connections_per_host(8)
|
.max_idle_connections_per_host(8)
|
||||||
.max_idle_connections(16)
|
.max_idle_connections(16)
|
||||||
.resolver(move |addr: &str| {
|
.resolver(move |addr: &str| {
|
||||||
let addr = match addr.find(":") {
|
let addr = match addr.find(':') {
|
||||||
Some(index) => addr[0..index].to_string(),
|
Some(index) => addr[0..index].to_string(),
|
||||||
None => addr.to_string()
|
None => addr.to_string()
|
||||||
};
|
};
|
||||||
@@ -427,17 +427,15 @@ impl HttpsDnsClient {
|
|||||||
for server in &servers {
|
for server in &servers {
|
||||||
if let Ok(res) = dns_client.send_udp_query(&addr, QueryType::A, server, true) {
|
if let Ok(res) = dns_client.send_udp_query(&addr, QueryType::A, server, true) {
|
||||||
for answer in &res.answers {
|
for answer in &res.answers {
|
||||||
match answer {
|
if let DnsRecord::A { addr, .. } = answer {
|
||||||
DnsRecord::A { addr, .. } => result.push(IpAddr::V4(addr.clone())),
|
result.push(IpAddr::V4(*addr))
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Ok(res) = dns_client.send_udp_query(&addr, QueryType::AAAA, server, true) {
|
if let Ok(res) = dns_client.send_udp_query(&addr, QueryType::AAAA, server, true) {
|
||||||
for answer in &res.answers {
|
for answer in &res.answers {
|
||||||
match answer {
|
if let DnsRecord::AAAA { addr, .. } = answer {
|
||||||
DnsRecord::AAAA { addr, .. } => result.push(IpAddr::V6(addr.clone())),
|
result.push(IpAddr::V6(*addr))
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -496,7 +494,7 @@ impl DnsClient for HttpsDnsClient {
|
|||||||
let response = self.agent
|
let response = self.agent
|
||||||
.post(doh_url)
|
.post(doh_url)
|
||||||
.set("Content-Type", "application/dns-message")
|
.set("Content-Type", "application/dns-message")
|
||||||
.send_bytes(&req_buffer.buffer.as_slice());
|
.send_bytes(req_buffer.buffer.as_slice());
|
||||||
|
|
||||||
match response {
|
match response {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
@@ -512,7 +510,7 @@ impl DnsClient for HttpsDnsClient {
|
|||||||
.take(4096)
|
.take(4096)
|
||||||
.read_to_end(&mut bytes)?;
|
.read_to_end(&mut bytes)?;
|
||||||
let mut buffer = VectorPacketBuffer::new();
|
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) {
|
if let Ok(packet) = DnsPacket::from_buffer(&mut buffer) {
|
||||||
return Ok(packet);
|
return Ok(packet);
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-5
@@ -20,13 +20,13 @@ impl HostsFilter {
|
|||||||
file.read_to_string(&mut text).unwrap();
|
file.read_to_string(&mut text).unwrap();
|
||||||
let mut map = HashMap::new();
|
let mut map = HashMap::new();
|
||||||
|
|
||||||
let list: Vec<_> = text.split("\n").collect();
|
let list: Vec<_> = text.split('\n').collect();
|
||||||
for s in list {
|
for s in list {
|
||||||
if s.is_empty() || s.starts_with("#") {
|
if s.is_empty() || s.starts_with('#') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let string = s.replace('\t', " ");
|
let string = s.replace('\t', " ");
|
||||||
let parts: Vec<_> = string.splitn(2, " ").collect();
|
let parts: Vec<_> = string.splitn(2, ' ').collect();
|
||||||
if parts.len() != 2 {
|
if parts.len() != 2 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -34,6 +34,7 @@ impl HostsFilter {
|
|||||||
let domain = parts[1].trim().to_owned();
|
let domain = parts[1].trim().to_owned();
|
||||||
if let Ok(addr) = ip.parse::<IpAddr>() {
|
if let Ok(addr) = ip.parse::<IpAddr>() {
|
||||||
if !domain.is_empty() {
|
if !domain.is_empty() {
|
||||||
|
#[allow(clippy::or_fun_call)]
|
||||||
map.entry(domain).or_insert(vec![addr]);
|
map.entry(domain).or_insert(vec![addr]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,10 +59,10 @@ impl DnsFilter for HostsFilter {
|
|||||||
for addr in list {
|
for addr in list {
|
||||||
match addr {
|
match addr {
|
||||||
IpAddr::V4(addr) if qtype == QueryType::A => {
|
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 => {
|
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) });
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -3,7 +3,7 @@ use std::net::TcpStream;
|
|||||||
|
|
||||||
pub fn read_packet_length(stream: &mut TcpStream) -> Result<u16> {
|
pub fn read_packet_length(stream: &mut TcpStream) -> Result<u16> {
|
||||||
let mut len_buffer = [0; 2];
|
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))
|
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[0] = (len >> 8) as u8;
|
||||||
len_buffer[1] = (len & 0xFF) as u8;
|
len_buffer[1] = (len & 0xFF) as u8;
|
||||||
|
|
||||||
stream.write(&len_buffer)?;
|
stream.write_all(&len_buffer)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+30
-38
@@ -1,7 +1,5 @@
|
|||||||
//! implements the DNS protocol in a transport agnostic fashion
|
//! implements the DNS protocol in a transport agnostic fashion
|
||||||
|
|
||||||
//use std::io::{Error, ErrorKind};
|
|
||||||
use std::cmp::Ordering;
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
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);
|
pub struct TransientTtl(pub u32);
|
||||||
|
|
||||||
impl PartialEq<TransientTtl> for TransientTtl {
|
impl PartialEq<TransientTtl> for TransientTtl {
|
||||||
fn eq(&self, _: &TransientTtl) -> bool {
|
fn eq(&self, other: &TransientTtl) -> bool {
|
||||||
true
|
self.0 == other.0
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialOrd<TransientTtl> for TransientTtl {
|
|
||||||
fn partial_cmp(&self, _: &TransientTtl) -> Option<Ordering> {
|
|
||||||
Some(Ordering::Equal)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,7 +192,7 @@ impl DnsRecord {
|
|||||||
((raw_addr >> 24) & 0xFF) as u8,
|
((raw_addr >> 24) & 0xFF) as u8,
|
||||||
((raw_addr >> 16) & 0xFF) as u8,
|
((raw_addr >> 16) & 0xFF) as u8,
|
||||||
((raw_addr >> 8) & 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) })
|
Ok(DnsRecord::A { domain, addr, ttl: TransientTtl(ttl) })
|
||||||
@@ -212,13 +204,13 @@ impl DnsRecord {
|
|||||||
let raw_addr4 = buffer.read_u32()?;
|
let raw_addr4 = buffer.read_u32()?;
|
||||||
let addr = Ipv6Addr::new(
|
let addr = Ipv6Addr::new(
|
||||||
((raw_addr1 >> 16) & 0xFFFF) as u16,
|
((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 >> 16) & 0xFFFF) as u16,
|
||||||
((raw_addr2 >> 0) & 0xFFFF) as u16,
|
(raw_addr2 & 0xFFFF) as u16,
|
||||||
((raw_addr3 >> 16) & 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 >> 16) & 0xFFFF) as u16,
|
||||||
((raw_addr4 >> 0) & 0xFFFF) as u16
|
(raw_addr4 & 0xFFFF) as u16
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(DnsRecord::AAAA { domain, addr, ttl: TransientTtl(ttl) })
|
Ok(DnsRecord::AAAA { domain, addr, ttl: TransientTtl(ttl) })
|
||||||
@@ -578,7 +570,7 @@ impl ResultCode {
|
|||||||
3 => ResultCode::NXDOMAIN,
|
3 => ResultCode::NXDOMAIN,
|
||||||
4 => ResultCode::NOTIMP,
|
4 => ResultCode::NOTIMP,
|
||||||
5 => ResultCode::REFUSED,
|
5 => ResultCode::REFUSED,
|
||||||
0 | _ => ResultCode::NOERROR
|
_ => ResultCode::NOERROR
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -642,7 +634,7 @@ impl DnsHeader {
|
|||||||
)?;
|
)?;
|
||||||
|
|
||||||
buffer.write_u8(
|
buffer.write_u8(
|
||||||
(self.rescode.clone() as u8)
|
(self.rescode as u8)
|
||||||
| ((self.checking_disabled as u8) << 4)
|
| ((self.checking_disabled as u8) << 4)
|
||||||
| ((self.authed_data as u8) << 5)
|
| ((self.authed_data as u8) << 5)
|
||||||
| ((self.z as u8) << 6)
|
| ((self.z as u8) << 6)
|
||||||
@@ -691,25 +683,25 @@ impl DnsHeader {
|
|||||||
|
|
||||||
impl fmt::Display for DnsHeader {
|
impl fmt::Display for DnsHeader {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(f, "DnsHeader:\n")?;
|
writeln!(f, "DnsHeader:")?;
|
||||||
write!(f, "\tid: {0}\n", self.id)?;
|
writeln!(f, "\tid: {0}", self.id)?;
|
||||||
|
|
||||||
write!(f, "\trecursion_desired: {0}\n", self.recursion_desired)?;
|
writeln!(f, "\trecursion_desired: {0}", self.recursion_desired)?;
|
||||||
write!(f, "\ttruncated_message: {0}\n", self.truncated_message)?;
|
writeln!(f, "\ttruncated_message: {0}", self.truncated_message)?;
|
||||||
write!(f, "\tauthoritative_answer: {0}\n", self.authoritative_answer)?;
|
writeln!(f, "\tauthoritative_answer: {0}", self.authoritative_answer)?;
|
||||||
write!(f, "\topcode: {0}\n", self.opcode)?;
|
writeln!(f, "\topcode: {0}", self.opcode)?;
|
||||||
write!(f, "\tresponse: {0}\n", self.response)?;
|
writeln!(f, "\tresponse: {0}", self.response)?;
|
||||||
|
|
||||||
write!(f, "\trescode: {:?}\n", self.rescode)?;
|
writeln!(f, "\trescode: {:?}", self.rescode)?;
|
||||||
write!(f, "\tchecking_disabled: {0}\n", self.checking_disabled)?;
|
writeln!(f, "\tchecking_disabled: {0}", self.checking_disabled)?;
|
||||||
write!(f, "\tauthed_data: {0}\n", self.authed_data)?;
|
writeln!(f, "\tauthed_data: {0}", self.authed_data)?;
|
||||||
write!(f, "\tz: {0}\n", self.z)?;
|
writeln!(f, "\tz: {0}", self.z)?;
|
||||||
write!(f, "\trecursion_available: {0}\n", self.recursion_available)?;
|
writeln!(f, "\trecursion_available: {0}", self.recursion_available)?;
|
||||||
|
|
||||||
write!(f, "\tquestions: {0}\n", self.questions)?;
|
writeln!(f, "\tquestions: {0}", self.questions)?;
|
||||||
write!(f, "\tanswers: {0}\n", self.answers)?;
|
writeln!(f, "\tanswers: {0}", self.answers)?;
|
||||||
write!(f, "\tauthoritative_entries: {0}\n", self.authoritative_entries)?;
|
writeln!(f, "\tauthoritative_entries: {0}", self.authoritative_entries)?;
|
||||||
write!(f, "\tresource_entries: {0}\n", self.resource_entries)?;
|
writeln!(f, "\tresource_entries: {0}", self.resource_entries)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -752,9 +744,9 @@ impl DnsQuestion {
|
|||||||
|
|
||||||
impl fmt::Display for DnsQuestion {
|
impl fmt::Display for DnsQuestion {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(f, "DnsQuestion:\n")?;
|
writeln!(f, "DnsQuestion:")?;
|
||||||
write!(f, "\tname: {0}\n", self.name)?;
|
writeln!(f, "\tname: {0}", self.name)?;
|
||||||
write!(f, "\trecord type: {:?}\n", self.qtype)?;
|
writeln!(f, "\trecord type: {:?}", self.qtype)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -946,7 +938,7 @@ impl DnsPacket {
|
|||||||
let mut test_buffer = VectorPacketBuffer::new();
|
let mut test_buffer = VectorPacketBuffer::new();
|
||||||
|
|
||||||
let mut size = self.header.binary_len();
|
let mut size = self.header.binary_len();
|
||||||
for ref question in &self.questions {
|
for question in &self.questions {
|
||||||
size += question.binary_len();
|
size += question.binary_len();
|
||||||
question.write(&mut test_buffer)?;
|
question.write(&mut test_buffer)?;
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -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
|
// Start querying name servers
|
||||||
loop {
|
loop {
|
||||||
@@ -162,21 +162,21 @@ impl DnsResolver for RecursiveDnsResolver {
|
|||||||
let ns_copy = ns.clone();
|
let ns_copy = ns.clone();
|
||||||
|
|
||||||
let server = format!("{}:{}", ns_copy.as_str(), 53);
|
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 we've got an actual answer, we're done!
|
||||||
if !response.answers.is_empty() && response.header.rescode == ResultCode::NOERROR {
|
if !response.answers.is_empty() && response.header.rescode == ResultCode::NOERROR {
|
||||||
let _ = self.context.cache.store(&response.answers);
|
let _ = self.context.cache.store(&response.answers);
|
||||||
let _ = self.context.cache.store(&response.authorities);
|
let _ = self.context.cache.store(&response.authorities);
|
||||||
let _ = self.context.cache.store(&response.resources);
|
let _ = self.context.cache.store(&response.resources);
|
||||||
return Ok(response.clone());
|
return Ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
if response.header.rescode == ResultCode::NXDOMAIN {
|
if response.header.rescode == ResultCode::NXDOMAIN {
|
||||||
if let Some(ttl) = response.get_ttl_from_soa() {
|
if let Some(ttl) = response.get_ttl_from_soa() {
|
||||||
let _ = self.context.cache.store_nxdomain(qname, qtype, ttl);
|
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
|
// 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
|
// If not, we'll have to resolve the ip of a NS record
|
||||||
let new_ns_name = match response.get_unresolved_ns(qname) {
|
let new_ns_name = match response.get_unresolved_ns(qname) {
|
||||||
Some(x) => x,
|
Some(x) => x,
|
||||||
None => return Ok(response.clone())
|
None => return Ok(response)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Recursively resolve the NS
|
// Recursively resolve the NS
|
||||||
@@ -204,7 +204,7 @@ impl DnsResolver for RecursiveDnsResolver {
|
|||||||
if let Some(new_ns) = recursive_response.get_random_a() {
|
if let Some(new_ns) = recursive_response.get_random_a() {
|
||||||
ns = new_ns.clone();
|
ns = new_ns.clone();
|
||||||
} else {
|
} else {
|
||||||
return Ok(response.clone());
|
return Ok(response);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -67,8 +67,8 @@ fn resolve_cnames(lookup_list: &[DnsRecord], results: &mut Vec<DnsPacket>, resol
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for ref rec in lookup_list {
|
for rec in lookup_list {
|
||||||
match **rec {
|
match *rec {
|
||||||
DnsRecord::CNAME { ref host, .. } | DnsRecord::SRV { ref host, .. } => {
|
DnsRecord::CNAME { ref host, .. } | DnsRecord::SRV { ref host, .. } => {
|
||||||
if let Ok(result2) = resolver.resolve(host, qtype, true) {
|
if let Ok(result2) = resolver.resolve(host, qtype, true) {
|
||||||
let new_unmatched = result2.get_unresolved_cnames(qtype);
|
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
|
// 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();
|
let cur_time = Utc::now().timestamp_millis();
|
||||||
if let Some(time) = working_ids.get(&key) {
|
if let Some(time) = working_ids.get(&key) {
|
||||||
if time + 100 > cur_time {
|
if time + 100 > cur_time {
|
||||||
|
|||||||
+1
-1
@@ -12,7 +12,7 @@ use crate::{Context, Settings};
|
|||||||
|
|
||||||
/// Starts UDP and TCP DNS-servers
|
/// Starts UDP and TCP DNS-servers
|
||||||
pub fn start_dns_server(context: &Arc<Mutex<Context>>, settings: &Settings) -> bool {
|
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;
|
let mut result = true;
|
||||||
if server_context.enable_udp {
|
if server_context.enable_udp {
|
||||||
|
|||||||
+9
-6
@@ -60,7 +60,7 @@ impl Keystore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_random_bytes(key: &[u8]) -> Self {
|
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 public = PublicKey::from(&secret);
|
||||||
let keypair = Keypair { secret, public };
|
let keypair = Keypair { secret, public };
|
||||||
let mut csprng = rand_old::thread_rng();
|
let mut csprng = rand_old::thread_rng();
|
||||||
@@ -147,10 +147,7 @@ impl Keystore {
|
|||||||
pub fn check(message: &[u8], public_key: &[u8], signature: &[u8]) -> bool {
|
pub fn check(message: &[u8], public_key: &[u8], signature: &[u8]) -> bool {
|
||||||
let key = PublicKey::from_bytes(public_key).expect("Wrong public key!");
|
let key = PublicKey::from_bytes(public_key).expect("Wrong public key!");
|
||||||
let signature = Signature::from_bytes(signature).unwrap();
|
let signature = Signature::from_bytes(signature).unwrap();
|
||||||
match key.verify(message, &signature) {
|
key.verify(message, &signature).is_ok()
|
||||||
Ok(_) => true,
|
|
||||||
Err(_) => false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn encrypt(&self, message: &[u8]) -> Bytes {
|
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 {
|
impl Clone for Keystore {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
let keypair = Keypair::from_bytes(&self.keypair.to_bytes()).unwrap();
|
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
|
/// Checks if some public key is "strong" enough to mine domains
|
||||||
/// TODO Optimize by caching Blakeout somewhere
|
/// TODO Optimize by caching Blakeout somewhere
|
||||||
pub fn check_public_key_strength(key: &Bytes, strength: u32) -> bool {
|
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
|
key_hash_difficulty(&bytes) >= strength
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-18
@@ -103,7 +103,7 @@ fn main() {
|
|||||||
let no_gui = true;
|
let no_gui = true;
|
||||||
|
|
||||||
if let Some(path) = opt_matches.opt_str("w") {
|
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") {
|
let config_name = match opt_matches.opt_str("c") {
|
||||||
None => SETTINGS_FILENAME.to_owned(),
|
None => SETTINGS_FILENAME.to_owned(),
|
||||||
@@ -113,18 +113,16 @@ fn main() {
|
|||||||
setup_logger(&opt_matches, console_attached);
|
setup_logger(&opt_matches, console_attached);
|
||||||
if let Some(status) = opt_matches.opt_str("s") {
|
if let Some(status) = opt_matches.opt_str("s") {
|
||||||
register(move |_, event| {
|
register(move |_, event| {
|
||||||
match event {
|
// TODO optimize for same data
|
||||||
Event::NetworkStatus { blocks, domains, keys, nodes } => {
|
if let Event::NetworkStatus { blocks, domains, keys, nodes } = event {
|
||||||
match File::create(Path::new(&status)) {
|
match File::create(Path::new(&status)) {
|
||||||
Ok(mut f) => {
|
Ok(mut f) => {
|
||||||
let data = format!("{{ \"blocks\":{}, \"domains\":{}, \"keys\":{}, \"nodes\":{} }}", blocks, domains, keys, nodes);
|
let data = format!("{{ \"blocks\":{}, \"domains\":{}, \"keys\":{}, \"nodes\":{} }}", blocks, domains, keys, nodes);
|
||||||
f.write_all(data.as_bytes()).expect("Error writing status file!");
|
f.write_all(data.as_bytes()).expect("Error writing status file!");
|
||||||
let _ = f.flush();
|
let _ = f.flush();
|
||||||
}
|
|
||||||
Err(_) => { error!("Error writing status file!"); }
|
|
||||||
}
|
}
|
||||||
|
Err(_) => { error!("Error writing status file!"); }
|
||||||
}
|
}
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
});
|
});
|
||||||
@@ -132,7 +130,7 @@ fn main() {
|
|||||||
|
|
||||||
info!(target: LOG_TARGET_MAIN, "Starting ALFIS {}", env!("CARGO_PKG_VERSION"));
|
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);
|
debug!(target: LOG_TARGET_MAIN, "Loaded settings: {:?}", &settings);
|
||||||
let chain: Chain = Chain::new(&settings, DB_NAME);
|
let chain: Chain = Chain::new(&settings, DB_NAME);
|
||||||
if opt_matches.opt_present("b") {
|
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());
|
info!("Blocks count: {}, domains count: {}, users count: {}", chain.get_height(), chain.get_domains_count(), chain.get_users_count());
|
||||||
let settings_copy = settings.clone();
|
let settings_copy = settings.clone();
|
||||||
let mut keys = Vec::new();
|
let mut keys = Vec::new();
|
||||||
if settings.key_files.len() > 0 {
|
if !settings.key_files.is_empty() {
|
||||||
for name in &settings.key_files {
|
for name in &settings.key_files {
|
||||||
match Keystore::from_file(name, "") {
|
match Keystore::from_file(name, "") {
|
||||||
None => {
|
None => {
|
||||||
@@ -239,7 +237,7 @@ fn main() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
#[cfg(feature = "webgui")]
|
#[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.
|
// 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),
|
WriteLogger::new(level, config, file),
|
||||||
])
|
])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
} else {
|
} else if let Err(e) = WriteLogger::init(level, config, file) {
|
||||||
if let Err(e) = WriteLogger::init(level, config, file) {
|
println!("Unable to initialize logger!\n{}", e);
|
||||||
println!("Unable to initialize logger!\n{}", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -138,7 +138,7 @@ impl Miner {
|
|||||||
|
|
||||||
mining.store(true, Ordering::SeqCst);
|
mining.store(true, Ordering::SeqCst);
|
||||||
current_job = Some(job.clone());
|
current_job = Some(job.clone());
|
||||||
Miner::mine_internal(Arc::clone(&context), job, mining.clone());
|
Miner::mine_internal(Arc::clone(context), job, mining.clone());
|
||||||
continue;
|
continue;
|
||||||
} else {
|
} else {
|
||||||
debug!("This job will wait for now");
|
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 {
|
} else {
|
||||||
let mut jobs = jobs.lock().unwrap();
|
let mut jobs = jobs.lock().unwrap();
|
||||||
@@ -169,7 +169,7 @@ impl Miner {
|
|||||||
if job.is_due() {
|
if job.is_due() {
|
||||||
mining.store(true, Ordering::SeqCst);
|
mining.store(true, Ordering::SeqCst);
|
||||||
current_job = Some(job.clone());
|
current_job = Some(job.clone());
|
||||||
Miner::mine_internal(Arc::clone(&context), job, mining.clone());
|
Miner::mine_internal(Arc::clone(context), job, mining.clone());
|
||||||
} else {
|
} else {
|
||||||
debug!("This job will wait for now");
|
debug!("This job will wait for now");
|
||||||
jobs.insert(0, job);
|
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) {
|
if !mining.load(Ordering::Relaxed) {
|
||||||
|
|||||||
+3
-5
@@ -2,6 +2,7 @@ extern crate serde;
|
|||||||
extern crate serde_json;
|
extern crate serde_json;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_cbor::Error;
|
||||||
|
|
||||||
use crate::Bytes;
|
use crate::Bytes;
|
||||||
|
|
||||||
@@ -21,11 +22,8 @@ pub enum Message {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Message {
|
impl Message {
|
||||||
pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, ()> {
|
pub fn from_bytes(bytes: Vec<u8>) -> Result<Message, Error> {
|
||||||
match serde_cbor::from_slice(bytes.as_slice()) {
|
serde_cbor::from_slice(bytes.as_slice())
|
||||||
Ok(cmd) => Ok(cmd),
|
|
||||||
Err(_) => Err(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn hand(app_version: &str, origin: &str, version: u32, public: bool, rand_id: &str) -> Self {
|
pub fn hand(app_version: &str, origin: &str, version: u32, public: bool, rand_id: &str) -> Self {
|
||||||
|
|||||||
+65
-76
@@ -69,7 +69,7 @@ impl Network {
|
|||||||
poll.registry().register(&mut server, SERVER, Interest::READABLE).expect("Error registering poll");
|
poll.registry().register(&mut server, SERVER, Interest::READABLE).expect("Error registering poll");
|
||||||
|
|
||||||
// Starting peer connections to bootstrap nodes
|
// 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 ui_timer = Instant::now();
|
||||||
let mut log_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 {
|
if self.peers.get_peers_count() == 0 && bootstrap_timer.elapsed().as_secs() > 60 {
|
||||||
warn!("Restarting swarm connections...");
|
warn!("Restarting swarm connections...");
|
||||||
// Starting peer connections to bootstrap nodes
|
// 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();
|
bootstrap_timer = Instant::now();
|
||||||
last_events_time = Instant::now();
|
last_events_time = Instant::now();
|
||||||
}
|
}
|
||||||
@@ -102,45 +102,42 @@ impl Network {
|
|||||||
//debug!("Event for server socket {} is {:?}", event.token().0, &event);
|
//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.
|
// If this is an event for the server, it means a connection is ready to be accepted.
|
||||||
let connection = server.accept();
|
let connection = server.accept();
|
||||||
match connection {
|
if let Ok((mut stream, mut address)) = connection {
|
||||||
Ok((mut stream, mut address)) => {
|
// Checking if it is an ipv4-mapped ipv6 if yes convert to ipv4
|
||||||
// Checking if it is an ipv4-mapped ipv6 if yes convert to ipv4
|
if address.is_ipv6() {
|
||||||
if address.is_ipv6() {
|
if let IpAddr::V6(ipv6) = address.ip() {
|
||||||
if let IpAddr::V6(ipv6) = address.ip() {
|
if let Some(ipv4) = ipv6.to_ipv4() {
|
||||||
if let Some(ipv4) = ipv6.to_ipv4() {
|
address = SocketAddr::V4(SocketAddrV4::new(ipv4, address.port()))
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
//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);
|
|
||||||
}
|
}
|
||||||
Err(_) => {}
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
//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) {
|
if let Err(e) = poll.registry().reregister(&mut server, SERVER, Interest::READABLE) {
|
||||||
panic!("Error reregistering server token!\n{}", e);
|
panic!("Error reregistering server token!\n{}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
token => {
|
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 _ = self.peers.close_peer(poll.registry(), &token);
|
||||||
let blocks = self.context.lock().unwrap().chain.get_height();
|
let blocks = self.context.lock().unwrap().chain.get_height();
|
||||||
let keys = self.context.lock().unwrap().chain.get_users_count();
|
let keys = self.context.lock().unwrap().chain.get_users_count();
|
||||||
@@ -227,8 +224,8 @@ impl Network {
|
|||||||
}
|
}
|
||||||
match peer.get_state().clone() {
|
match peer.get_state().clone() {
|
||||||
State::Connected => {
|
State::Connected => {
|
||||||
let mut stream = peer.get_stream();
|
let stream = peer.get_stream();
|
||||||
return match read_client_handshake(&mut stream) {
|
return match read_client_handshake(stream) {
|
||||||
Ok(key) => {
|
Ok(key) => {
|
||||||
let mut buf = [0u8; 32];
|
let mut buf = [0u8; 32];
|
||||||
buf.copy_from_slice(key.as_slice());
|
buf.copy_from_slice(key.as_slice());
|
||||||
@@ -251,8 +248,8 @@ impl Network {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
State::ServerHandshake => {
|
State::ServerHandshake => {
|
||||||
let mut stream = peer.get_stream();
|
let stream = peer.get_stream();
|
||||||
return match read_server_handshake(&mut stream) {
|
return match read_server_handshake(stream) {
|
||||||
Ok(data) => {
|
Ok(data) => {
|
||||||
if data.len() != 32 + 12 {
|
if data.len() != 32 + 12 {
|
||||||
warn!("Server handshake of {} bytes instead of {}", 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();
|
let stream = peer.get_stream();
|
||||||
read_message(&mut stream)
|
read_message(stream)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if data.is_ok() {
|
if let Ok(data) = data {
|
||||||
let data = {
|
let data = {
|
||||||
match self.peers.get_peer(&event.token()) {
|
match self.peers.get_peer(&event.token()) {
|
||||||
Some(peer) => {
|
Some(peer) => {
|
||||||
let data = data.unwrap();
|
|
||||||
match decode_message(&data, peer.get_cipher()) {
|
match decode_message(&data, peer.get_cipher()) {
|
||||||
Ok(data) => data,
|
Ok(data) => data,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
@@ -344,9 +340,9 @@ impl Network {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(e) => {
|
||||||
let peer = self.peers.get_peer(&event.token()).unwrap();
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -368,7 +364,7 @@ impl Network {
|
|||||||
Some(peer) => {
|
Some(peer) => {
|
||||||
match peer.get_state().clone() {
|
match peer.get_state().clone() {
|
||||||
State::Connecting => {
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
peer.set_state(State::ServerHandshake);
|
peer.set_state(State::ServerHandshake);
|
||||||
@@ -442,18 +438,16 @@ impl Network {
|
|||||||
if self.peers.is_our_own_connect(&rand_id) {
|
if self.peers.is_our_own_connect(&rand_id) {
|
||||||
warn!("Detected loop connect");
|
warn!("Detected loop connect");
|
||||||
State::SendLoop
|
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 {
|
} else {
|
||||||
if origin.eq(my_origin) && version == my_version {
|
warn!("Handshake from unsupported chain or version");
|
||||||
let peer = self.peers.get_mut_peer(token).unwrap();
|
State::Banned
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Message::Shake { app_version, origin, version, public, rand_id, height } => {
|
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!("Hashes are different, requesting block {} from {}", my_height, peer.get_addr().ip());
|
||||||
info!("My hash: {:?}, their hash: {:?}", &my_hash, &hash);
|
info!("My hash: {:?}, their hash: {:?}", &my_hash, &hash);
|
||||||
State::message(Message::GetBlock { index: my_height })
|
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 {
|
} else {
|
||||||
if active_count < MAX_NODES && random::<u8>() < 50 {
|
State::idle()
|
||||||
debug!("Requesting more peers from {}", peer.get_addr().ip());
|
|
||||||
State::message(Message::GetPeers)
|
|
||||||
} else {
|
|
||||||
State::idle()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Message::GetPeers => {
|
Message::GetPeers => {
|
||||||
let addr = {
|
let addr = {
|
||||||
let peer = self.peers.get_mut_peer(token).unwrap();
|
let peer = self.peers.get_mut_peer(token).unwrap();
|
||||||
peer.set_active(true);
|
peer.set_active(true);
|
||||||
peer.get_addr().clone()
|
peer.get_addr()
|
||||||
};
|
};
|
||||||
State::message(Message::Peers { peers: self.peers.get_peers_for_exchange(&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
|
// 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) {
|
while let Some(block) = self.future_blocks.remove(&next_index) {
|
||||||
if context.chain.check_new_block(&block) == BlockQuality::Good {
|
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);
|
context.chain.add_block(block);
|
||||||
} else {
|
} else {
|
||||||
warn!("Block {} in future blocks is bad!", block.index);
|
warn!("Block {} in future blocks is bad!", block.index);
|
||||||
@@ -656,21 +648,18 @@ impl Network {
|
|||||||
fn subscribe_to_bus(running: Arc<AtomicBool>) {
|
fn subscribe_to_bus(running: Arc<AtomicBool>) {
|
||||||
use crate::event::Event;
|
use crate::event::Event;
|
||||||
register(move |_uuid, e| {
|
register(move |_uuid, e| {
|
||||||
match e {
|
if let Event::ActionQuit = e {
|
||||||
Event::ActionQuit => {
|
running.store(false, Ordering::SeqCst);
|
||||||
running.store(false, Ordering::SeqCst);
|
return false;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
true
|
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 {
|
match cipher {
|
||||||
None => Ok(data.clone()),
|
None => Ok(data.to_owned()),
|
||||||
Some(chacha) => chacha.encrypt(data.as_slice())
|
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 {
|
match cipher {
|
||||||
None => Ok(data.clone()),
|
None => Ok(data.to_owned()),
|
||||||
Some(chacha) => chacha.decrypt(data.as_slice())
|
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;
|
let data_len = data.len() as u16;
|
||||||
//debug!("Sending {} bytes", data_len);
|
//debug!("Sending {} bytes", data_len);
|
||||||
//debug!("Message: {:?}", to_hex(&data));
|
//debug!("Message: {:?}", to_hex(&data));
|
||||||
let mut buf: Vec<u8> = Vec::with_capacity(data.len() + 2);
|
let mut buf: Vec<u8> = Vec::with_capacity(data.len() + 2);
|
||||||
buf.write_u16::<BigEndian>(data_len ^ 0xAAAA)?;
|
buf.write_u16::<BigEndian>(data_len ^ 0xAAAA)?;
|
||||||
buf.write_all(&data)?;
|
buf.write_all(data)?;
|
||||||
connection.write_all(&buf)?;
|
connection.write_all(&buf)?;
|
||||||
connection.flush()
|
connection.flush()
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -57,7 +57,7 @@ impl Peer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_addr(&self) -> SocketAddr {
|
pub fn get_addr(&self) -> SocketAddr {
|
||||||
self.addr.clone()
|
self.addr
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_stream(&mut self) -> &mut TcpStream {
|
pub fn get_stream(&mut self) -> &mut TcpStream {
|
||||||
|
|||||||
+75
-79
@@ -53,51 +53,48 @@ impl Peers {
|
|||||||
|
|
||||||
pub fn close_peer(&mut self, registry: &Registry, token: &Token) {
|
pub fn close_peer(&mut self, registry: &Registry, token: &Token) {
|
||||||
let peer = self.peers.get_mut(token);
|
let peer = self.peers.get_mut(token);
|
||||||
match peer {
|
if let Some(peer) = peer {
|
||||||
Some(peer) => {
|
let stream = peer.get_stream();
|
||||||
let stream = peer.get_stream();
|
let _ = stream.shutdown(Shutdown::Both);
|
||||||
let _ = stream.shutdown(Shutdown::Both);
|
let _ = registry.deregister(stream);
|
||||||
let _ = registry.deregister(stream);
|
match peer.get_state() {
|
||||||
match peer.get_state() {
|
State::Connecting => {
|
||||||
State::Connecting => {
|
debug!("Peer connection {} to {:?} has timed out", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} has timed out", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::Connected => {
|
||||||
State::Connected => {
|
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::Idle { .. } | State::Message { .. } => {
|
||||||
State::Idle { .. } | State::Message { .. } => {
|
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} disconnected", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::Error => {
|
||||||
State::Error => {
|
debug!("Peer connection {} to {:?} has shut down on error", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} has shut down on error", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::Banned => {
|
||||||
State::Banned => {
|
debug!("Peer connection {} to {:?} has shut down, banned", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} has shut down, banned", &token.0, &peer.get_addr());
|
self.ignored.insert(peer.get_addr().ip());
|
||||||
self.ignored.insert(peer.get_addr().ip().clone());
|
}
|
||||||
}
|
State::Offline { .. } => {
|
||||||
State::Offline { .. } => {
|
debug!("Peer connection {} to {:?} is offline", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} is offline", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::SendLoop => {
|
||||||
State::SendLoop => {
|
debug!("Peer connection {} from {:?} is a loop", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} from {:?} is a loop", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::Loop => {
|
||||||
State::Loop => {
|
debug!("Peer connection {} to {:?} is a loop", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} is a loop", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::Twin => {
|
||||||
State::Twin => {
|
debug!("Peer connection {} to {:?} is a twin", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} to {:?} is a twin", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::ServerHandshake => {
|
||||||
State::ServerHandshake => {
|
debug!("Peer connection {} from {:?} didn't shake hands", &token.0, &peer.get_addr());
|
||||||
debug!("Peer connection {} from {:?} didn't shake hands", &token.0, &peer.get_addr());
|
}
|
||||||
}
|
State::HandshakeFinished => {
|
||||||
State::HandshakeFinished => {
|
debug!("Peer connection {} from {:?} shook hands, but then failed", &token.0, &peer.get_addr());
|
||||||
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
|
if self.peers
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(_token, peer)| peer.get_addr().ip() == addr.ip())
|
.any(|(_token, peer)| peer.get_addr().ip() == addr.ip()) {
|
||||||
.is_some() {
|
|
||||||
//debug!("Skipping address from exchange: {}", &addr);
|
//debug!("Skipping address from exchange: {}", &addr);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.new_peers
|
if self.new_peers
|
||||||
.iter()
|
.iter()
|
||||||
.find(|a| a.ip().eq(&addr.ip()))
|
.any(|a| a.ip().eq(&addr.ip())) {
|
||||||
.is_some() {
|
|
||||||
//debug!("Skipping address from exchange: {}", &addr);
|
//debug!("Skipping address from exchange: {}", &addr);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -223,13 +218,13 @@ impl Peers {
|
|||||||
if !peer.get_state().is_loop() {
|
if !peer.get_state().is_loop() {
|
||||||
peer.set_state(State::Banned);
|
peer.set_state(State::Banned);
|
||||||
}
|
}
|
||||||
let ip = peer.get_addr().ip().clone();
|
let ip = peer.get_addr().ip();
|
||||||
self.close_peer(registry, token);
|
self.close_peer(registry, token);
|
||||||
self.ignored.insert(ip);
|
self.ignored.insert(ip);
|
||||||
match self.peers
|
match self.peers
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(_, p)| p.get_addr().ip() == ip)
|
.find(|(_, p)| p.get_addr().ip() == ip)
|
||||||
.map(|(t, _)| t.clone()) {
|
.map(|(t, _)| *t) {
|
||||||
None => {}
|
None => {}
|
||||||
Some(t) => {
|
Some(t) => {
|
||||||
self.close_peer(registry, &t);
|
self.close_peer(registry, &t);
|
||||||
@@ -240,7 +235,7 @@ impl Peers {
|
|||||||
|
|
||||||
pub fn ignore_ip(&mut self, ip: &IpAddr) {
|
pub fn ignore_ip(&mut self, ip: &IpAddr) {
|
||||||
info!("Adding {} to ignored peers", &ip);
|
info!("Adding {} to ignored peers", &ip);
|
||||||
self.ignored.insert(ip.clone());
|
self.ignored.insert(*ip);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn skip_peer_connection(&self, addr: &SocketAddr) -> bool {
|
pub fn skip_peer_connection(&self, addr: &SocketAddr) -> bool {
|
||||||
@@ -257,22 +252,19 @@ impl Peers {
|
|||||||
|
|
||||||
let random_time = random::<u64>() % PING_PERIOD;
|
let random_time = random::<u64>() % PING_PERIOD;
|
||||||
for (token, peer) in self.peers.iter_mut() {
|
for (token, peer) in self.peers.iter_mut() {
|
||||||
match peer.get_state() {
|
if let State::Idle { from } = peer.get_state() {
|
||||||
State::Idle { from } => {
|
if from.elapsed().as_secs() >= PING_PERIOD + random_time {
|
||||||
if from.elapsed().as_secs() >= PING_PERIOD + random_time {
|
// Sometimes we check for new peers instead of pinging
|
||||||
// Sometimes we check for new peers instead of pinging
|
let message = if nodes < MAX_NODES && random::<bool>() {
|
||||||
let message = if nodes < MAX_NODES && random::<bool>() {
|
Message::GetPeers
|
||||||
Message::GetPeers
|
} else {
|
||||||
} else {
|
Message::ping(height, hash.clone())
|
||||||
Message::ping(height, hash.clone())
|
};
|
||||||
};
|
|
||||||
|
|
||||||
peer.set_state(State::message(message));
|
peer.set_state(State::message(message));
|
||||||
let stream = peer.get_stream();
|
let stream = peer.get_stream();
|
||||||
registry.reregister(stream, token.clone(), Interest::WRITABLE).unwrap();
|
registry.reregister(stream, *token, Interest::WRITABLE).unwrap();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,11 +275,9 @@ impl Peers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If someone has more blocks we sync
|
// If someone has more blocks we sync
|
||||||
if nodes >= MIN_CONNECTED_NODES_START_SYNC {
|
if nodes >= MIN_CONNECTED_NODES_START_SYNC && height < max_height {
|
||||||
if height < max_height {
|
let count = min(max_height - height, nodes as u64);
|
||||||
let count = min(max_height - height, nodes as u64);
|
self.ask_blocks_from_peers(registry, height, height + count, have_blocks);
|
||||||
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
|
// If someone has less blocks (we mined a new block) we send a ping with our height
|
||||||
@@ -300,7 +290,7 @@ impl Peers {
|
|||||||
None => {}
|
None => {}
|
||||||
Some((token, peer)) => {
|
Some((token, peer)) => {
|
||||||
debug!("Peer {} is behind, sending ping", &peer.get_addr().ip());
|
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 }));
|
peer.set_state(State::message(Message::Ping { height, hash }));
|
||||||
self.update_behind_ping_time();
|
self.update_behind_ping_time();
|
||||||
}
|
}
|
||||||
@@ -323,9 +313,9 @@ impl Peers {
|
|||||||
for (token, peer) in self.peers.iter_mut() {
|
for (token, peer) in self.peers.iter_mut() {
|
||||||
if peer.get_state().need_reconnect() {
|
if peer.get_state().need_reconnect() {
|
||||||
let addr = peer.get_addr();
|
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());
|
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.set_state(State::Connecting);
|
||||||
peer.inc_reconnects();
|
peer.inc_reconnects();
|
||||||
peer.set_stream(stream);
|
peer.set_stream(stream);
|
||||||
@@ -346,7 +336,7 @@ impl Peers {
|
|||||||
None => {}
|
None => {}
|
||||||
Some((token, peer)) => {
|
Some((token, peer)) => {
|
||||||
debug!("Peer {} is higher than we are, requesting block {}", &peer.get_addr().ip(), height + 1);
|
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 }));
|
peer.set_state(State::message(Message::GetBlock { index: height + 1 }));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -366,7 +356,7 @@ impl Peers {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
debug!("Peer {} is higher than we are, requesting block {}", &peer.get_addr().ip(), index);
|
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 }));
|
peer.set_state(State::message(Message::GetBlock { index }));
|
||||||
index += 1;
|
index += 1;
|
||||||
if index > max_height {
|
if index > max_height {
|
||||||
@@ -390,7 +380,7 @@ impl Peers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Connecting to configured (bootstrap) 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();
|
let mut set = HashSet::new();
|
||||||
for peer in peers_addrs.iter() {
|
for peer in peers_addrs.iter() {
|
||||||
info!("Resolving address {}", peer);
|
info!("Resolving address {}", peer);
|
||||||
@@ -405,7 +395,7 @@ impl Peers {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
while addresses.len() > 0 {
|
while !addresses.is_empty() {
|
||||||
let addr = addresses.remove(0);
|
let addr = addresses.remove(0);
|
||||||
if !set.contains(&addr) {
|
if !set.contains(&addr) {
|
||||||
match self.connect_peer(&addr, registry, unique_token, yggdrasil_only) {
|
match self.connect_peer(&addr, registry, unique_token, yggdrasil_only) {
|
||||||
@@ -420,7 +410,7 @@ impl Peers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Copy others to new_peers, to connect later
|
// Copy others to new_peers, to connect later
|
||||||
if addresses.len() > 0 {
|
if !addresses.is_empty() {
|
||||||
self.new_peers.append(&mut addresses);
|
self.new_peers.append(&mut addresses);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -435,13 +425,13 @@ impl Peers {
|
|||||||
return Err(io::Error::from(io::ErrorKind::InvalidInput));
|
return Err(io::Error::from(io::ErrorKind::InvalidInput));
|
||||||
}
|
}
|
||||||
trace!("Connecting to peer {}", &addr);
|
trace!("Connecting to peer {}", &addr);
|
||||||
match TcpStream::connect(addr.clone()) {
|
match TcpStream::connect(*addr) {
|
||||||
Ok(mut stream) => {
|
Ok(mut stream) => {
|
||||||
//stream.set_nodelay(true)?;
|
//stream.set_nodelay(true)?;
|
||||||
let token = next(unique_token);
|
let token = next(unique_token);
|
||||||
trace!("Created connection {}, to peer {}", &token.0, &addr);
|
trace!("Created connection {}, to peer {}", &token.0, &addr);
|
||||||
registry.register(&mut stream, token, Interest::WRITABLE).unwrap();
|
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);
|
peer.set_public(true);
|
||||||
self.peers.insert(token, peer);
|
self.peers.insert(token, peer);
|
||||||
Ok(())
|
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
|
/// Gets new token from old token, mutating the last
|
||||||
pub fn next(current: &mut Token) -> Token {
|
pub fn next(current: &mut Token) -> Token {
|
||||||
let next = current.0;
|
let next = current.0;
|
||||||
|
|||||||
+2
-9
@@ -33,18 +33,11 @@ impl State {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_idle(&self) -> bool {
|
pub fn is_idle(&self) -> bool {
|
||||||
match self {
|
matches!(self, State::Idle { .. })
|
||||||
State::Idle { .. } => true,
|
|
||||||
_ => false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_loop(&self) -> bool {
|
pub fn is_loop(&self) -> bool {
|
||||||
match self {
|
matches!(self, State::Loop { .. } | State::SendLoop { .. })
|
||||||
State::Loop { .. } => true,
|
|
||||||
State::SendLoop { .. } => true,
|
|
||||||
_ => false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn disabled(&self) -> bool {
|
pub fn disabled(&self) -> bool {
|
||||||
|
|||||||
+14
-16
@@ -126,7 +126,7 @@ fn action_check_domain(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>
|
|||||||
let c = context.lock().unwrap();
|
let c = context.lock().unwrap();
|
||||||
if let Some(keystore) = c.get_keystore() {
|
if let Some(keystore) = c.get_keystore() {
|
||||||
let name = name.to_lowercase();
|
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!");
|
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
|
_ => threads
|
||||||
};
|
};
|
||||||
let status = Arc::new(Mutex::new(UiStatus::new(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();
|
let c = context.lock().unwrap();
|
||||||
|
|
||||||
register(move |_uuid, e| {
|
register(move |_uuid, e| {
|
||||||
@@ -221,7 +221,7 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
|
|||||||
let eval = match e {
|
let eval = match e {
|
||||||
Event::KeyCreated { path, public, hash } => {
|
Event::KeyCreated { path, public, hash } => {
|
||||||
load_domains(&mut context, &handle);
|
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!");
|
event_handle_luck(&handle, "Key successfully created! Don\\'t forget to save it!");
|
||||||
let mut s = format!("keystoreChanged('{}', '{}', '{}');", &path, &public, &hash);
|
let mut s = format!("keystoreChanged('{}', '{}', '{}');", &path, &public, &hash);
|
||||||
s.push_str(" showSuccess('New key mined successfully! Save it to a safe place!')");
|
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::KeyLoaded { path, public, hash } |
|
||||||
Event::KeySaved { path, public, hash } => {
|
Event::KeySaved { path, public, hash } => {
|
||||||
load_domains(&mut context, &handle);
|
load_domains(&mut context, &handle);
|
||||||
send_keys_to_ui(&mut context, &handle);
|
send_keys_to_ui(&context, &handle);
|
||||||
format!("keystoreChanged('{}', '{}', '{}');", &path, &public, &hash)
|
format!("keystoreChanged('{}', '{}', '{}');", &path, &public, &hash)
|
||||||
}
|
}
|
||||||
Event::MinerStarted | Event::KeyGeneratorStarted => {
|
Event::MinerStarted | Event::KeyGeneratorStarted => {
|
||||||
@@ -301,7 +301,7 @@ fn action_loaded(context: &Arc<Mutex<Context>>, web_view: &mut WebView<()>) {
|
|||||||
if status.mining {
|
if status.mining {
|
||||||
String::from("setLeftStatusBarText('Mining...'); showMiningIndicator(true, false);")
|
String::from("setLeftStatusBarText('Mining...'); showMiningIndicator(true, false);")
|
||||||
} else {
|
} else {
|
||||||
format!("setLeftStatusBarText('Idle'); showMiningIndicator(false, false);")
|
String::from("setLeftStatusBarText('Idle'); showMiningIndicator(false, false);")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Event::NetworkStatus { blocks, domains, keys, nodes } => {
|
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();
|
let mut keys = Vec::new();
|
||||||
for key in context.get_keystores() {
|
for key in context.get_keystores() {
|
||||||
let path = key.get_path().replace("\\", "/");
|
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.push(KeysForJS { file_name: parts[0].to_owned(), public: key.get_public().to_string() });
|
||||||
}
|
}
|
||||||
keys
|
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
|
// Check if yggdrasil only quality of zone is not violated
|
||||||
let zones = context.chain.get_zones();
|
let zones = context.chain.get_zones();
|
||||||
for z in zones {
|
for z in zones {
|
||||||
if z.name == data.zone {
|
if z.name == data.zone && z.yggdrasil {
|
||||||
if z.yggdrasil {
|
for record in &data.records {
|
||||||
for record in &data.records {
|
if !is_yggdrasil_record(record) {
|
||||||
if !is_yggdrasil_record(record) {
|
show_warning(web_view, &format!("Zone {} is Yggdrasil only, you cannot use IPs from clearnet!", &data.zone));
|
||||||
show_warning(web_view, &format!("Zone {} is Yggdrasil only, you cannot use IPs from clearnet!", &data.zone));
|
let _ = web_view.eval("domainMiningUnavailable();");
|
||||||
let _ = web_view.eval("domainMiningUnavailable();");
|
return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -562,6 +560,7 @@ fn format_event_now(kind: &str, message: &str) -> String {
|
|||||||
format!("addEvent('{}', '{}', '{}');", kind, time.format("%d.%m.%y %X"), message)
|
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) {
|
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 name = name.to_owned();
|
||||||
let encrypted = CryptoBox::encrypt(encryption.as_slice(), name.as_bytes()).expect("Error encrypting domain name!");
|
let encrypted = CryptoBox::encrypt(encryption.as_slice(), name.as_bytes()).expect("Error encrypting domain name!");
|
||||||
@@ -613,8 +612,7 @@ struct UiStatus {
|
|||||||
|
|
||||||
impl UiStatus {
|
impl UiStatus {
|
||||||
fn new(threads: usize) -> Self {
|
fn new(threads: usize) -> Self {
|
||||||
let mut speed = Vec::with_capacity(threads);
|
let speed =vec![0; threads];
|
||||||
speed.resize(threads, 0u64);
|
|
||||||
UiStatus { mining: false, syncing: false, synced_blocks: 0, sync_height: 0, max_diff: 0, speed }
|
UiStatus { mining: false, syncing: false, synced_blocks: 0, sync_height: 0, max_diff: 0, speed }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user