Skip to content

Commit 9104436

Browse files
committed
fix: validating memory pool to complete the transaction
1 parent fa9ff32 commit 9104436

File tree

1 file changed

+47
-7
lines changed

1 file changed

+47
-7
lines changed

1-simple-transactional-blockchain/blockchain.go

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,47 @@ func CreateBlockchain(difficulty int, rewardPerBlock float64, maxCoins float64)
6464
}
6565

6666
// addBlockData adds new data to the memory pool
67-
func (b *Blockchain) addBlockData(data BlockData) {
68-
if data.Validate(b) {
69-
b.MemoryPool = append(b.MemoryPool, data)
67+
func (b *Blockchain) addBlockData(data BlockData) error {
68+
if !data.Validate(b) {
69+
return fmt.Errorf("invalid transaction.")
7070
}
71+
72+
// Simulate adding the transaction to the memory pool and checking balances
73+
memoryPool := append(b.MemoryPool, data)
74+
if !validateMemoryPool(b, memoryPool) {
75+
return fmt.Errorf("You don't have enough coin to complete this transaction.")
76+
}
77+
78+
b.MemoryPool = memoryPool
79+
return nil
80+
}
81+
82+
// validateMemoryPool checks if all transactions in the memory pool are valid
83+
func validateMemoryPool(b *Blockchain, memoryPool []BlockData) bool {
84+
balances := make(map[string]float64)
85+
for _, block := range b.Chain {
86+
for _, data := range block.Data {
87+
if tx, ok := data.(Transaction); ok {
88+
balances[tx.From] -= tx.Amount
89+
balances[tx.To] += tx.Amount
90+
}
91+
}
92+
if block.Reward.Miner != "" {
93+
balances[block.Reward.Miner] += block.Reward.Amount
94+
}
95+
}
96+
97+
for _, data := range memoryPool {
98+
if tx, ok := data.(Transaction); ok {
99+
if balances[tx.From]-tx.Amount < 0 {
100+
return false
101+
}
102+
balances[tx.From] -= tx.Amount
103+
balances[tx.To] += tx.Amount
104+
}
105+
}
106+
107+
return true
71108
}
72109

73110
// mine mines a new block containing data from the memory pool
@@ -189,7 +226,10 @@ func main() {
189226
}
190227

191228
blockchain := c.Locals("blockchain").(*Blockchain)
192-
blockchain.addBlockData(data)
229+
err := blockchain.addBlockData(data)
230+
if err != nil {
231+
return c.Status(fiber.StatusForbidden).SendString(err.Error())
232+
}
193233

194234
response := fiber.Map{"message": "Data added to the memory pool"}
195235
return c.Status(fiber.StatusCreated).JSON(response)
@@ -199,9 +239,9 @@ func main() {
199239
app.Get("/chain", func(c *fiber.Ctx) error {
200240
blockchain := c.Locals("blockchain").(*Blockchain)
201241
response := fiber.Map{
202-
"chain": blockchain.Chain,
203-
"length": len(blockchain.Chain),
204-
"isValid": blockchain.isValid(),
242+
"chain": blockchain.Chain,
243+
"length": len(blockchain.Chain),
244+
"isValid": blockchain.isValid(),
205245
"minedCoins": blockchain.getMinedCoins(),
206246
}
207247
return c.Status(fiber.StatusOK).JSON(response)

0 commit comments

Comments
 (0)