add data structure for UTXOPool and update verify_new_block

pull/5/head
Minh Doan 7 years ago
parent 28d329e23a
commit c358fc754d
  1. 30
      blockchain/blockchain.go
  2. 2
      blockchain/blockchain_test.go
  3. 2
      blockchain/transaction.go
  4. 8
      blockchain/utxopool.go

@ -3,7 +3,6 @@ package blockchain
import ( import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"fmt"
) )
// Blockchain keeps a sequence of Blocks // Blockchain keeps a sequence of Blocks
@ -144,17 +143,38 @@ func (bc *Blockchain) AddNewTransferAmount(from, to string, amount int) *Blockch
} }
// VerifyNewBlock verifies if the new coming block is valid for the current blockchain. // VerifyNewBlock verifies if the new coming block is valid for the current blockchain.
func (bc *Blockchain) VerifyNewBlock(block *Block) bool { func (bc *Blockchain) VerifyNewBlock(utxopool *UTXOPool, block *Block) bool {
length := len(bc.blocks) length := len(bc.blocks)
if bytes.Compare(block.PrevBlockHash, bc.blocks[length-1].Hash) != 0 { if bytes.Compare(block.PrevBlockHash, bc.blocks[length-1].Hash) != 0 {
fmt.Println("MINh1")
return false return false
} }
if block.Timestamp < bc.blocks[length-1].Timestamp { if block.Timestamp < bc.blocks[length-1].Timestamp {
fmt.Println("MINh2")
return false return false
} }
// TODO(minhdoan): Check Transactions parts
if utxopool != nil {
for _, tx := range block.Transactions {
inTotal := 0
// Calculate the sum of TxInput
for _, in := range tx.TxInput {
inTxID := hex.EncodeToString(in.TxID)
if val, ok := utxopool.utxo[in.Address][inTxID]; ok {
inTotal += val
} else {
return false
}
}
outTotal := 0
// Calculate the sum of TxOutput
for _, out := range tx.TxOutput {
outTotal += out.Value
}
if inTotal != outTotal {
return false
}
}
}
return true return true
} }

@ -73,7 +73,7 @@ func TestVerifyNewBlock(t *testing.T) {
} }
newBlock := NewBlock([]*Transaction{tx}, bc.blocks[len(bc.blocks)-1].Hash) newBlock := NewBlock([]*Transaction{tx}, bc.blocks[len(bc.blocks)-1].Hash)
if !bc.VerifyNewBlock(newBlock) { if !bc.VerifyNewBlock(nil, newBlock) {
t.Error("failed to add a new valid block.") t.Error("failed to add a new valid block.")
} }
} }

@ -11,7 +11,7 @@ import (
// Transaction represents a Bitcoin transaction // Transaction represents a Bitcoin transaction
type Transaction struct { type Transaction struct {
ID []byte // 32 byte hash ID []byte // 32 byte hash
TxInput []TXInput TxInput []TXInput
TxOutput []TXOutput TxOutput []TXOutput
} }

@ -0,0 +1,8 @@
package blockchain
// UTXOPool stores transactions and balance associated with each address.
type UTXOPool struct {
// Mapping from address to a map of transaction id to that balance.
// The assumption here is that one address only appears once output array in a transaction.
utxo map[string]map[string]int
}
Loading…
Cancel
Save