1use 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#[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, pub transactions: Vec<Transaction>, }
27
28impl 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
41impl Block {
45 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 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}