From 1ea604af1354ac2b7c698cd4095a421d8c40c0e8 Mon Sep 17 00:00:00 2001 From: stinkymonkeyph Date: Tue, 13 Aug 2024 02:52:55 +0800 Subject: [PATCH] refactor: prevent disconnect of block and blockchain struct during block production --- blockchain/blockchain.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 0f2d458..14bca84 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -106,11 +106,13 @@ func (bc *Blockchain) AddTransactionToTransactionPool(txn *Transaction) { } } -func (bc *Blockchain) AddBlock(b *Block) { - m := map[string]bool{} - +func (bc *Blockchain) AddBlock(nonce int, txns []*Transaction) { nextBlockNumber := len(bc.Blocks) + b := NewBlock(bc.LastBlock().Hash(), nextBlockNumber, nonce, txns) + + m := map[string]bool{} + if b.PrevHash != bc.LastBlock().Hash() { log.Panic("Trying to add an invalid block, halting entire process") } @@ -182,8 +184,6 @@ func (bc *Blockchain) ProofOfWork() (int, []*Transaction) { func (bc *Blockchain) Mining() bool { nonce, txns := bc.ProofOfWork() - previousHash := bc.LastBlock().Hash() - block := NewBlock(previousHash, len(bc.Blocks), nonce, txns) - bc.AddBlock(block) + bc.AddBlock(nonce, txns) return true }