Clean up block.go; rework transaction hashing

This commit is contained in:
Ivan Kuznetsov 2017-09-10 12:02:46 +07:00
parent 80e320a16f
commit 942120679b
2 changed files with 41 additions and 15 deletions

View File

@ -8,7 +8,7 @@ import (
"time"
)
// Block keeps block headers
// Block represents a block in the blockchain
type Block struct {
Timestamp int64
Transactions []*Transaction
@ -34,26 +34,13 @@ func NewGenesisBlock(coinbase *Transaction) *Block {
return NewBlock([]*Transaction{coinbase}, []byte{})
}
// DeserializeBlock deserializes a block
func DeserializeBlock(d []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(d))
err := decoder.Decode(&block)
if err != nil {
log.Panic(err)
}
return &block
}
// HashTransactions returns a hash of the transactions in the block
func (b *Block) HashTransactions() []byte {
var txHashes [][]byte
var txHash [32]byte
for _, tx := range b.Transactions {
txHashes = append(txHashes, tx.ID)
txHashes = append(txHashes, tx.Hash())
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
@ -72,3 +59,16 @@ func (b *Block) Serialize() []byte {
return result.Bytes()
}
// DeserializeBlock deserializes a block
func DeserializeBlock(d []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(d))
err := decoder.Decode(&block)
if err != nil {
log.Panic(err)
}
return &block
}

View File

@ -29,7 +29,33 @@ func (tx Transaction) IsCoinbase() bool {
return len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1
}
// Serialize returns a serialized Transaction
func (tx Transaction) Serialize() []byte {
var encoded bytes.Buffer
enc := gob.NewEncoder(&encoded)
err := enc.Encode(tx)
if err != nil {
log.Panic(err)
}
return encoded.Bytes()
}
// Hash returns the hash of the Transaction
func (tx *Transaction) Hash() []byte {
var hash [32]byte
txCopy := *tx
txCopy.ID = []byte{}
hash = sha256.Sum256(txCopy.Serialize())
return hash[:]
}
// SetID sets ID of a transaction
// TODO: Remove this
func (tx *Transaction) SetID() {
var encoded bytes.Buffer
var hash [32]byte