From 271ac922b8e47a74fc467c2a4c54beae7a4fe60d Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Wed, 14 Apr 2021 21:48:49 +0300 Subject: Implement coinbase reward --- TODO.md | 2 +- src/handlers.rs | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/TODO.md b/TODO.md index 946ac4a..1e909cd 100644 --- a/TODO.md +++ b/TODO.md @@ -1,7 +1,6 @@ # TODO ## Simulation -- [ ] "Coinbase" ("by" of the first transaction of the block) should get rewarded for their efforts - [ ] Bank mechanism should be added. ## Tests @@ -36,3 +35,4 @@ - [x] Recover database from files - [.] POST requests to /block should be authenticated as well (2021-04-13 04:50, they now are but until we make error messages **Verbose** there's not much point in testing because I honestly cannot trace the code) - [X] Blocks should "play out" the transactions and execute transactions (2021-04-14 21:29) +- [X] "Coinbase" ("by" of the first transaction of the block) should get rewarded for their efforts (2021-04-14 21:48) diff --git a/src/handlers.rs b/src/handlers.rs index 420e82a..0dfea15 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -19,6 +19,7 @@ use warp::{http::StatusCode, reply}; use crate::PRIVATE_KEY; const BLOCK_TRANSACTION_COUNT: u8 = 10; +const BLOCK_REWARD: u8 = 3; // Encryption primitive type Aes128Cbc = Cbc; @@ -360,19 +361,26 @@ pub async fn authorized_propose_block( let pending_transactions = db.pending_transactions.read(); let mut users = db.users.write(); + let coinbase_fingerprint = new_block.transaction_list.get(0).unwrap(); + for fingerprint in new_block.transaction_list.iter() { - let transaction = pending_transactions.get(fingerprint).unwrap(); - let source = &transaction.source; - let target = &transaction.target; + if let Some(transaction) = pending_transactions.get(fingerprint) { + let source = &transaction.source; + let target = &transaction.target; - if let Some(from) = users.get_mut(source) { - from.balance -= transaction.amount; - } + if let Some(from) = users.get_mut(source) { + from.balance -= transaction.amount; + } - if let Some(to) = users.get_mut(target) { - to.balance += transaction.amount; + if let Some(to) = users.get_mut(target) { + to.balance += transaction.amount; + } } } + + if let Some(coinbase_user) = users.get_mut(coinbase_fingerprint) { + coinbase_user.balance += BLOCK_REWARD as i32; + } } { -- cgit v1.2.3-70-g09d2