Newer
Older
use serde::{Serialize, Deserialize};
use crate::types::hash::{H256, Hashable};
use crate::types::transaction::SignedTransaction;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Block {
pub header : Header,
pub content : Vec<SignedTransaction>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Header {
pub parent : H256,
pub nonce : u32,
pub difficulty : H256,
pub timestamp : u128,
pub merkle_root : H256,
return self.header.hash();
}
}
impl Hashable for Header {
fn hash(&self) -> H256 {
let bytes = bincode::serialize(&self).unwrap();
return ring::digest::digest(&ring::digest::SHA256, &bytes).into();
}
}
impl Block {
pub fn get_parent(&self) -> H256 {
self.header.difficulty
}
}
pub fn generate_genesis_block() -> Block {
// let mut rng = rand::r;
let emptyRoot = H256::from([0;32]);
return get_random_block(&emptyRoot);
}
pub fn get_random_block(parent: &H256) -> Block {
// let mut rng = rand::r;
let content: Vec<SignedTransaction> = Vec::new();
let bytes = bincode::serialize(&content).unwrap();
let merkle_root = ring::digest::digest(&ring::digest::SHA256, &bytes).into();
let difficulty = H256::from([255u8; 32]);
let header = Header{
parent: *parent,
nonce: rand::random::<u32>(),
timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis(),
merkle_root: merkle_root,
difficulty: difficulty,
};
Block{
header: header,
content: content,
}
}
#[cfg(any(test, test_utilities))]
pub fn generate_random_block(parent: &H256) -> Block {
// let mut rng = rand::r;
let content: Vec<SignedTransaction> = Vec::new();
let bytes = bincode::serialize(&content).unwrap();
let merkle_root = ring::digest::digest(&ring::digest::SHA256, &bytes).into();
let difficulty = crate::types::hash::generate_random_hash();
let header = Header{
parent: *parent,
nonce: rand::random::<u32>(),
timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis(),
merkle_root: merkle_root,
difficulty: difficulty,
};
Block{
header: header,
content: content,
}
}