From 55d0620afe4ea59fdbff2fc55c08776dfda4bdf6 Mon Sep 17 00:00:00 2001 From: stinkymonkeyph Date: Wed, 7 Aug 2024 01:05:45 +0800 Subject: [PATCH] feat: invalidate block addition when adding block with invalid prev hash --- blockchain/blockchain.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 17124b8..119bbec 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -68,7 +68,12 @@ func (bc *Blockchain) AddBlock(b *Block) { nextBlockHeight := len(bc.Blocks) + if b.PrevHash != bc.LastBlock().Hash() { + log.Panic("Trying to add an invalid block, halting entire process") + } + for index, txn := range b.Transactions { + txn.Status = constants.STATUS_SUCCESS m[txn.TransactioHash] = true balance := bc.WalletIndex.CalculateBalance(txn.From) log.Printf("\n\nsender balance -> %d \n\n", balance) @@ -101,7 +106,13 @@ func (bc *Blockchain) LastBlock() *Block { func (bc *Blockchain) CopyTransactionPool() []*Transaction { t := make([]*Transaction, 0) for _, txn := range bc.TransactionPool { - t = append(t, NewTransaction(txn.From, txn.To, txn.Value, txn.Data)) + senderBalance := bc.WalletIndex.CalculateBalance(txn.From) + if txn.From != constants.BLOCKCHAIN_AIRDROP_ADDRESS { + if senderBalance < int(txn.Value) { + txn.Status = constants.STATUS_FAILED + } + } + t = append(t, txn) } return t } @@ -126,12 +137,10 @@ func (bc *Blockchain) ProofOfWork() (int, []*Transaction) { } func (bc *Blockchain) Mining() bool { - log.Println("Start proof of work") nonce, txns := bc.ProofOfWork() previousHash := bc.LastBlock().Hash() block := NewBlock(previousHash, nonce) block.Transactions = txns bc.AddBlock(block) - log.Println("Found solution") return true }