diff options
| author | littleblack111 <littleblack11111@gmail.com> | 2025-10-22 13:50:20 +0800 |
|---|---|---|
| committer | littleblack111 <littleblack11111@gmail.com> | 2025-10-23 22:00:56 +0800 |
| commit | bb1e8a814aa3b1846e51f0d1a6c344af94228e96 (patch) | |
| tree | 91af937d232a79ab63a464aafa1e58683d5a976b | |
| parent | a54046f51ec00aab7a4f3a35e67b7422d92db98b (diff) | |
use hashchain
| -rw-r--r-- | src/blocks.rs | 13 | ||||
| -rw-r--r-- | src/hash_chain.rs | 29 |
2 files changed, 31 insertions, 11 deletions
diff --git a/src/blocks.rs b/src/blocks.rs index 57fbab8..53f9326 100644 --- a/src/blocks.rs +++ b/src/blocks.rs @@ -4,7 +4,11 @@ use std::ops::Deref; use serde::{Deserialize, Serialize}; -use crate::{ZERO_PREFIX_AMOUNT, transaction::Transaction}; +use crate::{ + ZERO_PREFIX_AMOUNT, + hash_chain::{self, HashChain}, + transaction::Transaction, +}; use std::sync::{ Arc, @@ -29,7 +33,7 @@ impl Block { Self { prev_hash: prev_hash .unwrap_or(&[]) - .to_vec(), // special blocks + .to_vec(), trans, pow: None, } @@ -79,7 +83,6 @@ impl Block { } break; } - println!("{i}"); i = i.wrapping_add(step); } }); @@ -120,13 +123,13 @@ impl CryptoDigest for Block { #[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)] pub struct BlockChain { - pub blocks: Vec<Block>, + pub blocks: HashChain<Block>, } impl BlockChain { pub fn new(blocks: Vec<Block>) -> Self { Self { - blocks, + blocks: HashChain::new(blocks), } } diff --git a/src/hash_chain.rs b/src/hash_chain.rs index 2079e1c..b87ac61 100644 --- a/src/hash_chain.rs +++ b/src/hash_chain.rs @@ -1,13 +1,31 @@ use std::ops::Deref; use bincode::Encode; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] pub struct HashChain<T: Encode> { data: Vec<(Vec<u8>, T)>, // Vector of (hash, value) pairs } +impl<T: Encode> Default for HashChain<T> { + fn default() -> Self { + Self { + data: Default::default(), + } + } +} + impl<T: Encode> HashChain<T> { + pub fn new(data: Vec<T>) -> Self { + let mut this = Self::default(); + for i in data { + this.push(i); + } + this + } + fn push(&mut self, data: T) { let prev_hash = self .data @@ -31,19 +49,18 @@ impl<T: Encode> HashChain<T> { } fn verify(&self, from_hash: &[u8]) -> bool { - let start_idx = self + let i = self .data .iter() .position(|x| x.0 == from_hash) .unwrap(); - (start_idx - ..self - .data - .len()) + (i..self + .data + .len()) .all(|i| { Self::hash( if i == 0 { - &Vec::default() + &[] } else { &self.data[i - 1].0 }, |
