From f4929e520d3fa8efa2795ec0c8966dade5b4794d Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Sun, 11 Aug 2024 14:44:13 +0700 Subject: [PATCH] Update blockchain.rs --- pi-nexus-blockchain/src/blockchain.rs | 55 ++++++++------------------- 1 file changed, 15 insertions(+), 40 deletions(-) diff --git a/pi-nexus-blockchain/src/blockchain.rs b/pi-nexus-blockchain/src/blockchain.rs index 526e34e56..a47764d72 100644 --- a/pi-nexus-blockchain/src/blockchain.rs +++ b/pi-nexus-blockchain/src/blockchain.rs @@ -1,48 +1,23 @@ -// blockchain.rs (updated) +// blockchain.rs (new) -// ... +use crate::block::Block; +use std::collections::VecDeque; -impl Blockchain { - // ... - - pub fn validate_block(&self, block: &Block) -> bool { - let previous_block_hash = self.chain.last().unwrap().hash.clone(); - if block.header.previous_hash != previous_block_hash { - return false; - } - if block.header.difficulty_target != self.difficulty_target { - return false; - } - if block.header.timestamp <= self.chain.last().unwrap().header.timestamp { - return false; - } - if !self.validate_transactions(&block.transactions) { - return false; - } - true - } +pub struct Blockchain { + pub chain: VecDeque, +} - fn validate_transactions(&self, transactions: &Vec) -> bool { - for transaction in transactions { - if !self.validate_transaction(transaction) { - return false; - } +impl Blockchain { + pub fn new() -> Self { + let genesis_block = Block::new(0, "0", vec![]); + Blockchain { + chain: VecDeque::from(vec![genesis_block]), } - true } - fn validate_transaction(&self, transaction: &Transaction) -> bool { - // TO DO: implement transaction validation logic - true - } - - pub fn mine_block(&mut self) { - let block = self.create_block(); - if self.validate_block(&block) { - self.chain.push(block); - self.pending_transactions.clear(); - } else { - println!("Invalid block!"); - } + pub fn add_block(&mut self, transactions: Vec) { + let previous_hash = self.chain.back().unwrap().hash.clone(); + let new_block = Block::new(self.chain.len() as u64, &previous_hash, transactions); + self.chain.push_back(new_block); } }