Skip to content

Commit

Permalink
Merge pull request #3 from nguyenphuminh/patch-0.3.3
Browse files Browse the repository at this point in the history
Fix invalid transactions
  • Loading branch information
nguyenphuminh authored Jan 13, 2022
2 parents aa83049 + 3762241 commit 1bc5986
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
20 changes: 17 additions & 3 deletions jechain.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,16 @@ class Block {
}

static hasValidTransactions(block, chain) {
let gas = 0, reward = 0;
let gas = 0, reward = 0, balances = {};

block.data.forEach(transaction => {
console.log(transaction);
if (transaction.from !== MINT_PUBLIC_ADDRESS) {
if (!balances[transaction.from]) {
balances[transaction.from] = chain.getBalance(transaction.from);
} else {
balances[transaction.from] -= transaction.amount + transaction.gas;
}
gas += transaction.gas;
} else {
reward = transaction.amount;
Expand All @@ -40,7 +46,8 @@ class Block {
return (
reward - gas === chain.reward &&
block.data.every(transaction => Transaction.isValid(transaction, chain)) &&
block.data.filter(transaction => transaction.from === MINT_PUBLIC_ADDRESS).length === 1
block.data.filter(transaction => transaction.from === MINT_PUBLIC_ADDRESS).length === 1 &&
Object.values(balances).every(balance => balance >= 0)
);
}
}
Expand Down Expand Up @@ -74,8 +81,15 @@ class Blockchain {
}

addTransaction(transaction) {
let balance = this.getBalance(transaction.from) - transaction.amount - transaction.gas;

if (Transaction.isValid(transaction, this)) {
this.transactions.forEach(tx => {
if (tx.from === transaction.from) {
balance -= tx.amount + tx.gas;
}
});

if (Transaction.isValid(transaction, this) && balance >= 0) {
this.transactions.push(transaction);
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jecoin",
"version": "0.3.2",
"version": "0.3.3",
"description": "",
"main": "jecoin.js",
"scripts": {
Expand Down

0 comments on commit 1bc5986

Please sign in to comment.