From 942120679bd8fd845df826314c592cb508396edf Mon Sep 17 00:00:00 2001 From: Ivan Kuznetsov Date: Sun, 10 Sep 2017 12:02:46 +0700 Subject: [PATCH] Clean up block.go; rework transaction hashing --- block.go | 30 +++++++++++++++--------------- transaction.go | 26 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/block.go b/block.go index 3baaa46..b98c79c 100644 --- a/block.go +++ b/block.go @@ -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 +} diff --git a/transaction.go b/transaction.go index e5176d6..99e4282 100644 --- a/transaction.go +++ b/transaction.go @@ -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