Skip to content
Snippets Groups Projects
block.rs 2.38 KiB
Newer Older
Gerui Wang's avatar
Gerui Wang committed
use serde::{Serialize, Deserialize};
use crate::types::hash::{H256, Hashable};
qh11's avatar
qh11 committed
use crate::types::transaction::SignedTransaction;
use std::time::{SystemTime, UNIX_EPOCH};
Gerui Wang's avatar
Gerui Wang committed

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Block {
qh11's avatar
qh11 committed
    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,
Gerui Wang's avatar
Gerui Wang committed
}

impl Hashable for Block {
    fn hash(&self) -> H256 {
qh11's avatar
qh11 committed
        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();
Gerui Wang's avatar
Gerui Wang committed
    }
}

impl Block {
    pub fn get_parent(&self) -> H256 {
qh11's avatar
qh11 committed
        self.header.parent
Gerui Wang's avatar
Gerui Wang committed
    }

    pub fn get_difficulty(&self) -> H256 {
qh11's avatar
qh11 committed
        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,
Gerui Wang's avatar
Gerui Wang committed
    }
}

#[cfg(any(test, test_utilities))]
pub fn generate_random_block(parent: &H256) -> Block {
qh11's avatar
qh11 committed
    // 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,
    }
}