-
Notifications
You must be signed in to change notification settings - Fork 1
First pass at a Rust based decentralized ledger #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| [package] | ||
| name = "rustbucks" | ||
| version = "0.1.0" | ||
| edition = "2021" | ||
|
|
||
| [dependencies] | ||
| bincode = "1.3.3" | ||
| chrono = "0.4.38" | ||
| fixed = "1.27.0" | ||
| serde = "1.0.203" | ||
| sha2 = "0.10.8" | ||
| tokio = { version = "1.38.0", features = ["full"] } | ||
| tracing = "0.1.40" | ||
| tracing-subscriber = "0.3.18" |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| pub mod model; | ||
| pub mod mine; |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| use chrono::Utc; | ||
| use fixed::types::I32F32; | ||
| use rustbucks::{mine::mine_pending_transactions, model::{blockchain::Blockchain, transaction::Transaction}}; | ||
|
|
||
|
|
||
| fn main() { | ||
| let bc = Blockchain::new(); | ||
|
|
||
| let transaction = Transaction { | ||
| amount: I32F32::from_num(50), | ||
| sender: "me".to_string(), | ||
| receiver: "you".to_string(), | ||
| timestamp: Utc::now().timestamp(), | ||
| }; | ||
|
|
||
| let new_block = mine_pending_transactions(&bc, vec![transaction]); | ||
| dbg!(new_block); | ||
| } |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| use chrono::Utc; | ||
| use sha2::Sha256; | ||
| use sha2::Digest; | ||
| use tracing::instrument; | ||
|
|
||
| use crate::model::{blockchain::Blockchain, transaction::Transaction, block::Block}; | ||
|
|
||
| #[instrument] | ||
| pub fn mine_pending_transactions(blockchain: &Blockchain, pending_transactions: Vec<Transaction>) -> Block { | ||
| // for now try to include all current transactions into the next block, | ||
| // theoretically we could cherry pick a subset of the transactions | ||
| let last_block = blockchain | ||
| .chain | ||
| .last() | ||
| .expect("couldnt get last block. this shouldn't happen."); | ||
|
|
||
| let mut hasher = Sha256::new(); | ||
|
|
||
| //compute hash of the previous block | ||
| hasher.update(format!("{:?}", last_block)); | ||
| let previous_hash = format!("{:x}", hasher.finalize()); | ||
| let timestamp = Utc::now().timestamp(); | ||
|
|
||
| let mut new_block = Block { | ||
| index: last_block.index + 1, | ||
| transactions: pending_transactions.clone().into_iter().collect(), | ||
| previous_hash, | ||
| timestamp, | ||
| nonce: 0, | ||
| }; | ||
|
|
||
| loop { | ||
| hasher = Sha256::new(); | ||
| hasher.update(format!("{:?}", new_block)); | ||
| let hash = format!("{:x}", hasher.finalize()); | ||
| if hash.starts_with(&blockchain.target_hash_prefix) { | ||
| break; | ||
| } | ||
|
|
||
| new_block.nonce = new_block.nonce + 1; | ||
| } | ||
|
|
||
| new_block | ||
| } |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| use super::transaction::Transaction; | ||
| use sha2::Sha256; | ||
| use sha2::Digest; | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct Block { | ||
| pub index: u64, | ||
| pub transactions: Vec<Transaction>, | ||
| pub nonce: u64, | ||
| pub previous_hash: String, | ||
| pub timestamp: i64, | ||
| } | ||
|
|
||
| impl Block { | ||
| pub fn hash(&self) -> String { | ||
| let mut hasher = Sha256::new(); | ||
| hasher.update(format!("{:?}", self)); | ||
| format!("{:x}", hasher.finalize()) | ||
| } | ||
| } |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,263 @@ | ||
| use std::collections::HashSet; | ||
|
|
||
| use fixed::types::I32F32; | ||
| use sha2::Digest; | ||
| use sha2::Sha256; | ||
|
|
||
| use super::{block::Block, transaction::Transaction}; | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct Blockchain { | ||
| pub chain: Vec<Block>, | ||
|
|
||
| //this is for adjusting the difficulty | ||
| pub target_hash_prefix: String, | ||
|
|
||
| pub confirmed_transactions: HashSet<Transaction>, | ||
| } | ||
|
|
||
| #[derive(Debug, PartialEq)] | ||
| pub enum BlockchainError { | ||
| UnknownTransaction, | ||
| IncorrectProof, | ||
| InvalidIndex, | ||
| PreviousHashDoesNotMatch, | ||
| } | ||
|
|
||
| impl Blockchain { | ||
| pub fn new() -> Self { | ||
| let mut hasher = Sha256::new(); | ||
| hasher.update("let there be light"); | ||
| let timestamp = 0; | ||
|
|
||
| let genesis_transaction = Transaction { | ||
| sender: "".to_string(), | ||
| receiver: "".to_string(), | ||
| amount: I32F32::from_num(0.0), | ||
| timestamp, | ||
| }; | ||
|
|
||
| let confirmed_transactions = vec![genesis_transaction.clone()].into_iter().collect(); | ||
|
|
||
| let chain = vec![Block { | ||
| index: 0, | ||
| transactions: vec![genesis_transaction], | ||
| nonce: 41, | ||
| previous_hash: format!("{:x}", hasher.finalize()), | ||
| timestamp, | ||
| }]; | ||
|
|
||
| Blockchain { | ||
| chain, | ||
| target_hash_prefix: "00".to_string(), // pretty low difficulty | ||
| confirmed_transactions, | ||
| } | ||
| } | ||
|
|
||
| //new blocks could originate from those mined on other nodes | ||
| //or those mined on this node | ||
| pub fn add_new_block(&mut self, new_block: Block) -> Result<(), BlockchainError> { | ||
| let last = self | ||
| .chain | ||
| .last() | ||
| .expect("could not get last block in chain, this should never happen"); | ||
|
|
||
| //verify the last block hash is correct | ||
| let last_hash = last.hash(); | ||
| if last_hash != new_block.previous_hash { | ||
| return Err(BlockchainError::PreviousHashDoesNotMatch); | ||
| } | ||
|
|
||
| // verify that the hash of the block hash the target prefix | ||
| if !new_block.hash().starts_with(&self.target_hash_prefix) { | ||
| return Err(BlockchainError::IncorrectProof); // somebody gave tried giving us a bad block | ||
| } | ||
|
|
||
| //verify the index is correct | ||
| if new_block.index != last.index + 1 { | ||
| return Err(BlockchainError::InvalidIndex); | ||
| } | ||
|
|
||
| self.chain.push(new_block.clone()); | ||
| // so we can easily look them up later | ||
| for transaction in new_block.transactions { | ||
| self.confirmed_transactions.insert(transaction); | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| // things to validate | ||
| // 1. Previous hash matches actual hash of previous block | ||
| // 2. Hashes all have the target prefix | ||
MoonKraken marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| pub fn is_valid(&self) -> bool { | ||
| let mut prev_hash = if let Some(first) = self.chain.first() { | ||
| first.hash() | ||
| } else { | ||
| return false; | ||
| }; | ||
|
|
||
| for block in &self.chain[1..] { | ||
| if !prev_hash.starts_with(&self.target_hash_prefix) || prev_hash != prev_hash { | ||
| return false; | ||
| } | ||
|
|
||
| prev_hash = block.hash(); | ||
| } | ||
|
|
||
| if !prev_hash.starts_with(&self.target_hash_prefix) { | ||
| return false; | ||
| } | ||
|
|
||
| true | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod test { | ||
| use fixed::types::I32F32; | ||
|
|
||
| use crate::model::{block::Block, blockchain::BlockchainError, transaction::Transaction}; | ||
|
|
||
| use super::Blockchain; | ||
|
|
||
| // this is really just to discover the nonce of the first block | ||
| // should we ever need to update the contents of the block | ||
| #[test] | ||
| pub fn discover_nonce_for_first_block() { | ||
| let chain = Blockchain::new(); | ||
| let mut first_block = chain.chain.first().expect("should have genesis block").clone(); | ||
|
|
||
| while !first_block.hash().starts_with(&chain.target_hash_prefix) { | ||
| first_block.nonce = first_block.nonce + 1; | ||
| } | ||
|
|
||
| println!("nonce discovered:"); | ||
| dbg!(first_block.nonce); | ||
| } | ||
|
|
||
| #[test] | ||
| pub fn is_valid_returns_false_for_chain_with_incorrect_target_prefix() { | ||
| let mut chain = Blockchain::new(); | ||
| let previous_hash = chain | ||
| .chain | ||
| .first() | ||
| .expect("should have genesis block") | ||
| .hash(); | ||
|
|
||
| let block_with_hash_without_target_prefix = Block { | ||
| index: 1, | ||
| nonce: 0, | ||
| previous_hash, | ||
| transactions: vec![Transaction { | ||
| sender: "Billy".to_string(), | ||
| receiver: "Timmy".to_string(), | ||
| timestamp: 0, | ||
| amount: I32F32::from_num(1), | ||
| }], | ||
| timestamp: 0, | ||
| }; | ||
|
|
||
| dbg!(block_with_hash_without_target_prefix.hash()); // make sure this doesn't miraculously start with 00 | ||
|
|
||
| chain.chain.push(block_with_hash_without_target_prefix); | ||
|
|
||
| assert_eq!(chain.is_valid(), false); | ||
| } | ||
|
|
||
| #[test] | ||
| pub fn is_valid_returns_false_for_chain_with_invalid_hash() { | ||
| let invalid_block = Block { | ||
| index: 1, | ||
| nonce: 0, | ||
| previous_hash: "asdf".to_string(), // this is incorrect | ||
| transactions: vec![Transaction { | ||
| sender: "Billy".to_string(), | ||
| receiver: "Timmy".to_string(), | ||
| timestamp: 0, | ||
| amount: I32F32::from_num(1), | ||
| }], | ||
| timestamp: 0, | ||
| }; | ||
|
|
||
| let mut chain = Blockchain::new(); | ||
| chain.chain.push(invalid_block); | ||
|
|
||
| assert_eq!(chain.is_valid(), false); | ||
| } | ||
|
|
||
| #[test] | ||
| pub fn should_not_add_invalid_block_invalid_nonce() { | ||
| let mut chain = Blockchain::new(); | ||
| let previous_hash = chain.chain.first().expect("genesis block").hash(); | ||
| let invalid_block = Block { | ||
| index: 1, | ||
| // there is a chance this nonce will unintentionally yield a correct hash, | ||
| // but it is unlikely. if this test ever fails | ||
| // try changing the nonce to something else | ||
| // and it will probably be fixed | ||
| nonce: 0, | ||
| previous_hash, | ||
| transactions: vec![Transaction { | ||
| sender: "Billy".to_string(), | ||
| receiver: "Timmy".to_string(), | ||
| timestamp: 0, | ||
| amount: I32F32::from_num(1), | ||
| }], | ||
| timestamp: 0, | ||
| }; | ||
|
|
||
| let res = chain.add_new_block(invalid_block); | ||
|
|
||
| assert_eq!(res, Err(BlockchainError::IncorrectProof)); | ||
| } | ||
|
|
||
| #[test] | ||
| pub fn should_not_add_invalid_block_invalid_previous_hash() { | ||
| let invalid_block = Block { | ||
| index: 1, | ||
| nonce: 245, | ||
| previous_hash: "6109c0d119501c326c8a613b9d99069caf7372566e5725a72b47cc9d737f304d" | ||
| .to_string(), // this is incorrect | ||
| transactions: vec![Transaction { | ||
| sender: "me".to_string(), | ||
| receiver: "you".to_string(), | ||
| timestamp: 0, | ||
| amount: I32F32::from_num(50), | ||
| }], | ||
| timestamp: 1719876768, | ||
| }; | ||
|
|
||
| let mut chain = Blockchain::new(); | ||
| let res = chain.add_new_block(invalid_block); | ||
|
|
||
| assert_eq!(res, Err(BlockchainError::PreviousHashDoesNotMatch)); | ||
| } | ||
|
|
||
| #[test] | ||
| pub fn should_add_valid_block() { | ||
| let mut chain = Blockchain::new(); | ||
| let previous_hash = chain.chain.first().expect("genesis block").hash(); | ||
| let mut valid_block = Block { | ||
| index: 1, | ||
| nonce: 245, | ||
| previous_hash, | ||
| transactions: vec![Transaction { | ||
| sender: "me".to_string(), | ||
| receiver: "you".to_string(), | ||
| timestamp: 1719876768, | ||
| amount: I32F32::from_num(50), | ||
| }], | ||
| timestamp: 1719876768, | ||
| }; | ||
|
|
||
| // "mine" for a good nonce | ||
| while !valid_block.hash().starts_with(&chain.target_hash_prefix) { | ||
| valid_block.nonce = valid_block.nonce + 1; | ||
| } | ||
|
|
||
| let res = chain.add_new_block(valid_block); | ||
|
|
||
| assert_eq!(res, Ok(())); | ||
| } | ||
| } | ||
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| pub mod transaction; | ||
| pub mod blockchain; | ||
| pub mod block; | ||
| pub mod node; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Question: Do you plan on keeping these confirmed transactions in BlockChain?
I'm assuming this is for either testing purposes or intended for the genesis transactions only? If it's the latter, we can probably create a genesis Block with genesis transactions instead, right?
The reason I'm asking is that it feels like duplicated data since we have transactions in Block too.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
confirmed transactions is intended to have all transactions from every block in the chain, solely to facilitate O(1) lookups.
that said - completely separate thing but I'm not entirely sure we need to have any transactions in the genesis block.