Files
Alfis/src/blockchain/block.rs
T

97 lines
2.9 KiB
Rust
Raw Normal View History

2019-12-01 22:45:25 +01:00
extern crate serde;
extern crate serde_json;
use std::fmt::Debug;
use serde::{Serialize, Deserialize};
use crate::bytes::Bytes;
use crate::Transaction;
2021-04-22 16:31:42 +02:00
use crate::blockchain::hash_utils::{hash_difficulty, key_hash_difficulty};
2019-12-01 22:45:25 +01:00
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
pub struct Block {
pub index: u64,
pub timestamp: i64,
pub version: u32,
pub difficulty: u32,
2019-12-01 22:45:25 +01:00
pub random: u32,
pub nonce: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction: Option<Transaction>,
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub prev_block_hash: Bytes,
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub hash: Bytes,
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub pub_key: Bytes,
#[serde(default, skip_serializing_if = "Bytes::is_zero")]
pub signature: Bytes,
2019-12-01 22:45:25 +01:00
}
impl Block {
pub fn new(transaction: Option<Transaction>, pub_key: Bytes, prev_block_hash: Bytes, difficulty: u32) -> Self {
2019-12-01 22:45:25 +01:00
Block {
index: 0,
timestamp: 0,
version: 0,
difficulty,
2019-12-01 22:45:25 +01:00
random: 0,
nonce: 0,
transaction,
prev_block_hash,
hash: Bytes::default(),
pub_key,
signature: Bytes::default()
2019-12-01 22:45:25 +01:00
}
}
pub fn from_all_params(index: u64, timestamp: i64, version: u32, difficulty: u32, random: u32, nonce: u64, prev_block_hash: Bytes, hash: Bytes, pub_key: Bytes, signature: Bytes, transaction: Option<Transaction>) -> Self {
Block {
index,
timestamp,
version,
difficulty,
random,
nonce,
transaction,
prev_block_hash,
hash,
pub_key,
signature
}
}
2019-12-01 22:45:25 +01:00
pub fn is_genesis(&self) -> bool {
self.index == 1 && self.transaction.is_none() && self.prev_block_hash == Bytes::default()
2019-12-01 22:45:25 +01:00
}
pub fn as_bytes(&self) -> Vec<u8> {
Vec::from(serde_json::to_string(&self).unwrap().as_bytes())
}
2021-04-22 16:31:42 +02:00
/// Checks if this block is superior than the other
pub fn is_better_than(&self, other: &Block) -> bool {
2021-04-22 16:31:42 +02:00
if self.transaction.is_some() && other.transaction.is_none() {
return true;
}
2021-04-22 16:31:42 +02:00
let my_diff = hash_difficulty(self.hash.as_slice());
let it_diff = hash_difficulty(other.hash.as_slice());
if my_diff > it_diff {
return true;
}
let my_diff = key_hash_difficulty(self.hash.as_slice());
let it_diff = key_hash_difficulty(other.hash.as_slice());
if my_diff > it_diff {
return true;
}
let my_diff = hash_difficulty(self.signature.as_slice());
let it_diff = hash_difficulty(other.signature.as_slice());
if my_diff > it_diff {
return true;
}
if self.nonce < other.nonce {
return true;
}
2021-04-22 16:31:42 +02:00
false
}
2019-12-01 22:45:25 +01:00
}