block_chain/
block.rs

1//!
2//! This is the block module.<br>
3//! The bock struct is used to create a block.
4//!
5
6use crate::wallet::Transaction;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use sha2::{Digest, Sha256};
10use std::cmp::PartialEq;
11use std::fmt::Write;
12
13/// This is the block struct.<br>
14/// It includes index, timestamp, <br>
15/// hash previous hash and data field.
16///
17#[derive(Debug, Serialize, Deserialize, Clone)]
18pub struct Block {
19    pub block_index: u64,
20    pub timestamp: u64,
21    pub previous_hash: String,
22    pub hash: String,
23    pub data: Value,
24    pub miner_address: String, // Address of the miner who mined this block
25    pub transactions: Vec<Transaction>, // Transactions included in this block
26}
27
28///
29/// Adding Trait PartialEq.
30///
31impl PartialEq for Block {
32    fn eq(&self, other: &Self) -> bool {
33        self.block_index == other.block_index
34            && self.timestamp == other.timestamp
35            && self.previous_hash == other.previous_hash
36            && self.hash == other.hash
37            && self.data == other.data
38    }
39}
40
41///
42/// Functions for Struct Block.
43///
44impl Block {
45    ///
46    /// Function to create a new block struct.
47    ///
48    pub fn new(
49        block_index: u64,
50        timestamp: u64,
51        previous_hash: String,
52        data: Value,
53        miner_address: String,
54        transactions: Vec<Transaction>,
55    ) -> Block {
56        let mut block = Block {
57            block_index,
58            timestamp,
59            previous_hash,
60            hash: String::new(),
61            data,
62            miner_address,
63            transactions,
64        };
65        block.hash = block.calculate_hash();
66        block
67    }
68
69    ///
70    /// This function calculates the hash for the block.<br>
71    /// The hash is SHA256.
72    ///
73    pub fn calculate_hash(&self) -> String {
74        let mut hasher = Sha256::new();
75        hasher.update(self.block_index.to_string());
76        hasher.update(self.timestamp.to_string());
77        hasher.update(&self.previous_hash);
78        hasher.update(&self.data.to_string());
79        let result = hasher.finalize();
80        let mut hash = String::new();
81        for byte in result {
82            write!(&mut hash, "{:02x}", byte).unwrap();
83        }
84        hash
85    }
86}