-
-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
15 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<Block>, | ||
} | ||
|
||
fn validate_transactions(&self, transactions: &Vec<Transaction>) -> 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<crate::transaction::Transaction>) { | ||
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); | ||
} | ||
} |