/
nirvand
/
rust-blockchain
Обзор
Документация
Войти
/
nirvand
/
rust-blockchain
Код
Запросы
1
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/blockchain.rs
68 строк
2 KB
Nirvand
feat: basic block and blockchain implementation
20 мар 2025, 17:27
20 мар 2025, 17:27
0bba18c
Код
Авторство
О чём код?
use sha2::{Sha256, Digest}; // Для хеширования use chrono::prelude::*; // для работы с датами и временем #[derive(Debug, Clone)] pub struct Block { pub index: u32, pub timestamp: String, pub data: String, pub previous_hash: String, pub hash: String, } impl Block { pub fn new(index: u32, data: String, previous_hash: String) -> Self { let timestamp = Utc::now().to_rfc3339(); let hash = Self::calculate_hash(index, ×tamp, &data, &previous_hash); Block { index, timestamp, data, previous_hash, hash, } } fn calculate_hash(index: u32, timestamp: &str, data: &str, previous_hash: &str) -> String { let input = format!("{}{}{}{}", index, timestamp, data, previous_hash); let mut hasher = Sha256::new(); hasher.update(input.as_bytes()); format!("{:x}", hasher.finalize()) } } #[derive(Debug)] pub struct Blockchain { pub blocks: Vec<Block>, } impl Blockchain { pub fn new() -> Self { let genesis_block = Block::new(0, "Genesis Block".to_string(), "0".to_string()); Blockchain { blocks: vec![genesis_block], } } pub fn add_block(&mut self, data: String) { let prev_block = self.blocks.last().unwrap(); let new_block = Block::new(prev_block.index + 1, data, prev_block.hash.clone()); self.blocks.push(new_block); } pub fn is_valid(&self) -> bool { for i in 1..self.blocks.len() { let prev = &self.blocks[i - 1]; let curr = &self.blocks[i]; if curr.previous_hash != prev.hash { return false; } if curr.hash != Block::calculate_hash(curr.index, &curr.timestamp, &curr.data, &curr.previous_hash) { return false; } } true } }