Code reformatting.

This commit is contained in:
Revertron
2021-06-09 20:36:36 +02:00
parent 2d12fd0447
commit d513c29cfe
40 changed files with 546 additions and 815 deletions
+6 -4
View File
@@ -2,11 +2,13 @@ extern crate serde;
extern crate serde_json;
use std::fmt::Debug;
use serde::{Serialize, Deserialize};
use crate::bytes::Bytes;
use crate::Transaction;
use serde::{Deserialize, Serialize};
use crate::blockchain::hash_utils::{hash_difficulty, key_hash_difficulty};
use crate::blockchain::transaction::TransactionType;
use crate::bytes::Bytes;
use crate::Transaction;
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct Block {
@@ -25,7 +27,7 @@ pub struct Block {
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub signature: Bytes,
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction: Option<Transaction>,
pub transaction: Option<Transaction>
}
impl Block {
+39 -35
View File
@@ -10,15 +10,15 @@ use chrono::Utc;
use log::{debug, error, info, trace, warn};
use sqlite::{Connection, State, Statement};
use crate::{Block, Bytes, check_domain, get_domain_zone, is_yggdrasil_record, Keystore, Transaction};
use crate::blockchain::hash_utils::*;
use crate::blockchain::transaction::DomainData;
use crate::blockchain::types::{BlockQuality, MineResult, Options, ZoneData};
use crate::blockchain::types::BlockQuality::*;
use crate::blockchain::types::MineResult::*;
use crate::blockchain::types::{BlockQuality, MineResult, Options, ZoneData};
use crate::commons::constants::*;
use crate::keystore::check_public_key_strength;
use crate::settings::Settings;
use crate::{check_domain, get_domain_zone, is_yggdrasil_record, Block, Bytes, Keystore, Transaction};
use rand::prelude::IteratorRandom;
const TEMP_DB_NAME: &str = ":memory:";
@@ -43,7 +43,7 @@ const SQL_GET_USERS_COUNT: &str = "SELECT count(DISTINCT pub_key) FROM blocks;";
const SQL_GET_OPTIONS: &str = "SELECT * FROM options;";
/// Max possible block index
const MAX:u64 = i64::MAX as u64;
const MAX: u64 = i64::MAX as u64;
pub struct Chain {
origin: Bytes,
@@ -52,7 +52,7 @@ pub struct Chain {
max_height: u64,
db: Connection,
zones: Vec<ZoneData>,
signers: RefCell<SignersCache>,
signers: RefCell<SignersCache>
}
impl Chain {
@@ -104,8 +104,8 @@ impl Chain {
last_block = self.get_block(start - 1);
if let Some(last) = &last_block {
last_full_block = match &last.transaction {
None => { self.get_last_full_block(last.index, None) }
Some(_) => { Some(last.clone()) }
None => self.get_last_full_block(last.index, None),
Some(_) => Some(last.clone())
};
}
}
@@ -271,8 +271,10 @@ impl Chain {
}
let block = match self.last_full_block {
None => { return None; }
Some(ref block) => { block.clone() }
None => {
return None;
}
Some(ref block) => block.clone()
};
// TODO maybe make some config option to mine signing blocks above?
let sign_count = self.get_height() - block.index;
@@ -293,7 +295,8 @@ impl Chain {
let signers: HashSet<Bytes> = self.get_block_signers(&block).into_iter().collect();
let mut rng = rand::thread_rng();
let keystore = keys.iter()
let keystore = keys
.iter()
.filter(|keystore| signers.contains(&keystore.get_public()))
.filter(|keystore| {
for index in block.index..=self.get_height() {
@@ -304,7 +307,8 @@ impl Chain {
}
}
true
}).choose(&mut rng);
})
.choose(&mut rng);
if let Some(keystore) = keystore {
info!("We have an honor to mine signing block!");
let mut block = Block::new(None, Bytes::default(), last_hash, SIGNER_DIFFICULTY);
@@ -356,7 +360,9 @@ impl Chain {
statement.bind(5, block.random as i64)?;
statement.bind(6, block.nonce as i64)?;
match &block.transaction {
None => { statement.bind(7, "")?; }
None => {
statement.bind(7, "")?;
}
Some(transaction) => {
statement.bind(7, transaction.to_string().as_str())?;
}
@@ -417,7 +423,9 @@ impl Chain {
if let Some(block) = &self.last_full_block {
if block.index < before {
match pub_key {
None => { return Some(block.clone()); }
None => {
return Some(block.clone());
}
Some(key) => {
if block.pub_key.deref().eq(key) {
return Some(block.clone());
@@ -500,7 +508,7 @@ impl Chain {
let zones: Vec<_> = zones_text.split("\n").collect();
for zone in zones {
let yggdrasil = zone == "ygg" || zone == "anon";
result.push(ZoneData {name: zone.to_owned(), yggdrasil})
result.push(ZoneData { name: zone.to_owned(), yggdrasil })
}
result
}
@@ -553,7 +561,7 @@ impl Chain {
let new_id = !self.is_domain_in_blockchain(height, &identity_hash);
let time = last.timestamp + NEW_DOMAINS_INTERVAL - Utc::now().timestamp();
if new_id && time > 0 {
return Cooldown { time }
return Cooldown { time };
}
}
@@ -598,8 +606,8 @@ impl Chain {
pub fn get_domain_info(&self, domain: &str) -> Option<String> {
match self.get_domain_transaction(domain) {
None => { None }
Some(transaction) => { Some(transaction.data) }
None => None,
Some(transaction) => Some(transaction.data)
}
}
@@ -668,30 +676,28 @@ impl Chain {
pub fn get_height(&self) -> u64 {
match self.last_block {
None => { 0u64 }
Some(ref block) => {
block.index
}
None => 0u64,
Some(ref block) => block.index
}
}
pub fn get_last_hash(&self) -> Bytes {
match &self.last_block {
None => { Bytes::default() }
Some(block) => { block.hash.clone() }
None => Bytes::default(),
Some(block) => block.hash.clone()
}
}
pub fn get_soa_serial(&self) -> u32 {
match &self.last_full_block {
None => { 0 }
Some(block) => { block.timestamp as u32 }
None => 0,
Some(block) => block.timestamp as u32
}
}
pub fn next_allowed_full_block(&self) -> u64 {
match self.last_full_block {
None => { self.get_height() + 1 }
None => self.get_height() + 1,
Some(ref block) => {
if block.index < BLOCK_SIGNERS_START {
self.get_height() + 1
@@ -743,7 +749,7 @@ impl Chain {
SIGNER_DIFFICULTY
}
}
Some(t) => { self.get_difficulty_for_transaction(&t) }
Some(t) => self.get_difficulty_for_transaction(&t)
};
if block.difficulty < difficulty {
warn!("Block difficulty is lower than needed");
@@ -776,8 +782,8 @@ impl Chain {
if let Some(transaction) = &block.transaction {
let current_height = match last_block {
None => { 0 }
Some(block) => { block.index }
None => 0,
Some(block) => block.index
};
// If this domain is available to this public key
if !self.is_id_available(current_height, &transaction.identity, &block.pub_key) {
@@ -921,17 +927,15 @@ impl Chain {
match transaction.class.as_ref() {
CLASS_DOMAIN => {
return match serde_json::from_str::<DomainData>(&transaction.data) {
Ok(_) => {
DOMAIN_DIFFICULTY
}
Ok(_) => DOMAIN_DIFFICULTY,
Err(_) => {
warn!("Error parsing DomainData from {:?}", transaction);
u32::MAX
}
}
}
CLASS_ORIGIN => { ORIGIN_DIFFICULTY }
_ => { u32::MAX }
CLASS_ORIGIN => ORIGIN_DIFFICULTY,
_ => u32::MAX
}
}
@@ -1009,11 +1013,11 @@ impl SignersCache {
#[cfg(test)]
pub mod tests {
use log::LevelFilter;
use simplelog::{ColorChoice, ConfigBuilder, TerminalMode, TermLogger};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use simplelog::{ColorChoice, ConfigBuilder, TermLogger, TerminalMode};
use crate::{Chain, Settings, Block};
use crate::{Block, Chain, Settings};
fn init_logger() {
let config = ConfigBuilder::new()
+16 -16
View File
@@ -1,10 +1,12 @@
use crate::Context;
use std::sync::{Mutex, Arc};
use crate::dns::filter::DnsFilter;
use crate::dns::protocol::{DnsPacket, QueryType, DnsRecord, DnsQuestion, ResultCode, TransientTtl};
use std::sync::{Arc, Mutex};
#[allow(unused_imports)]
use log::{trace, debug, info, warn, error};
use log::{debug, error, info, trace, warn};
use crate::blockchain::transaction::DomainData;
use crate::dns::filter::DnsFilter;
use crate::dns::protocol::{DnsPacket, DnsQuestion, DnsRecord, QueryType, ResultCode, TransientTtl};
use crate::Context;
pub struct BlockchainFilter {
context: Arc<Mutex<Context>>
@@ -16,8 +18,8 @@ impl BlockchainFilter {
}
}
const NAME_SERVER: & str = "ns.alfis.name";
const SERVER_ADMIN: & str = "admin.alfis.name";
const NAME_SERVER: &str = "ns.alfis.name";
const SERVER_ADMIN: &str = "admin.alfis.name";
impl DnsFilter for BlockchainFilter {
fn lookup(&self, qname: &str, qtype: QueryType) -> Option<DnsPacket> {
@@ -64,8 +66,10 @@ impl DnsFilter for BlockchainFilter {
Some(data) => {
trace!("Found data for domain {}", &search);
let mut data: DomainData = match serde_json::from_str(&data) {
Err(_) => { return None; }
Ok(data) => { data }
Err(_) => {
return None;
}
Ok(data) => data
};
let mut answers: Vec<DnsRecord> = Vec::new();
let a_record = qtype == QueryType::A || qtype == QueryType::AAAA;
@@ -153,11 +157,7 @@ impl DnsFilter for BlockchainFilter {
for answer in answers {
packet.answers.push(answer);
}
packet.authorities.push( DnsRecord::NS {
domain: zone,
host: String::from(NAME_SERVER),
ttl: TransientTtl(600)
});
packet.authorities.push(DnsRecord::NS { domain: zone, host: String::from(NAME_SERVER), ttl: TransientTtl(600) });
//trace!("Returning packet: {:?}", &packet);
Some(packet)
} else {
@@ -170,7 +170,7 @@ impl DnsFilter for BlockchainFilter {
BlockchainFilter::add_soa_record(zone, serial, &mut packet);
//trace!("Returning packet: {:?}", &packet);
Some(packet)
}
};
}
}
@@ -189,7 +189,7 @@ impl BlockchainFilter {
retry: 300,
expire: 604800,
minimum: 60,
ttl: TransientTtl(60),
ttl: TransientTtl(60)
});
}
+8 -6
View File
@@ -1,8 +1,9 @@
use std::convert::TryInto;
use blakeout::Blakeout;
use sha2::{Digest, Sha256};
use crate::{Block, Bytes, Keystore};
use sha2::{Sha256, Digest};
use std::convert::TryInto;
/// Checks block's hash and returns true on valid hash or false otherwise
pub fn check_block_hash(block: &Block) -> bool {
@@ -32,7 +33,7 @@ pub fn hash_identity(identity: &str, key: Option<&Bytes>) -> Bytes {
let base = hash_sha256(identity.as_bytes());
let identity = hash_sha256(&base);
match key {
None => { Bytes::from_bytes(&identity) }
None => Bytes::from_bytes(&identity),
Some(key) => {
let mut buf = Vec::new();
buf.append(&mut base.clone());
@@ -85,9 +86,10 @@ pub fn hash_sha256(data: &[u8]) -> Vec<u8> {
#[cfg(test)]
mod tests {
use crate::blockchain::hash_utils::hash_sha256;
use std::convert::TryInto;
use crate::blockchain::hash_utils::hash_sha256;
#[test]
#[ignore]
pub fn test_hash() {
@@ -111,9 +113,9 @@ mod tests {
#[test]
#[ignore]
fn test_hash_is_good() {
let hash = vec!(0u8,0u8,0u8,255,255,255,255,255);
let hash = vec![0u8, 0u8, 0u8, 255, 255, 255, 255, 255];
let bytes: [u8; 8] = hash[..8].try_into().unwrap();
let int = u64::from_be_bytes(bytes);
println!("int = {}", int);
}
}
}
+1 -2
View File
@@ -2,10 +2,9 @@ pub use block::Block;
pub use chain::Chain;
pub use transaction::Transaction;
pub mod transaction;
pub mod block;
pub mod chain;
pub mod filter;
pub mod hash_utils;
pub mod transaction;
pub mod types;
+5 -5
View File
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use crate::blockchain::hash_utils::*;
use crate::bytes::Bytes;
use crate::dns::protocol::DnsRecord;
use crate::{CLASS_ORIGIN, CLASS_DOMAIN};
use crate::{CLASS_DOMAIN, CLASS_ORIGIN};
extern crate serde;
extern crate serde_json;
@@ -23,7 +23,7 @@ pub struct Transaction {
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub encryption: Bytes,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub data: String,
pub data: String
}
impl Transaction {
@@ -64,7 +64,7 @@ impl Transaction {
pub fn get_domain_data(&self) -> Option<DomainData> {
if self.class == CLASS_DOMAIN {
if let Ok(data) = serde_json::from_str::<DomainData>(&self.data) {
return Some(data)
return Some(data);
}
}
None
@@ -73,7 +73,7 @@ impl Transaction {
/// Gets a type of transaction
pub fn get_type(what: &Option<Transaction>) -> TransactionType {
match what {
None => { TransactionType::Signing }
None => TransactionType::Signing,
Some(transaction) => {
if transaction.class == CLASS_DOMAIN {
return TransactionType::Domain;
@@ -116,7 +116,7 @@ pub struct DomainData {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub records: Vec<DnsRecord>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub contacts: Vec<ContactsData>,
pub contacts: Vec<ContactsData>
}
impl DomainData {
+5 -4
View File
@@ -1,4 +1,5 @@
use std::fmt::{Display, Formatter};
use serde::{Deserialize, Serialize};
/// Represents a result of block check on block's arrival
@@ -9,7 +10,7 @@ pub enum BlockQuality {
Future,
Rewind,
Bad,
Fork,
Fork
}
#[derive(Debug)]
@@ -20,13 +21,13 @@ pub enum MineResult {
WrongKey,
WrongZone,
NotOwned,
Cooldown { time: i64 },
Cooldown { time: i64 }
}
#[derive(Debug)]
pub struct Options {
pub origin: String,
pub version: u32,
pub version: u32
}
impl Options {
@@ -42,7 +43,7 @@ impl Options {
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ZoneData {
pub name: String,
pub yggdrasil: bool,
pub yggdrasil: bool
}
impl Display for ZoneData {