diff --git a/block.go b/block.go index 1d04b4f..4a62cad 100644 --- a/block.go +++ b/block.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "crypto/sha256" "encoding/gob" "log" "time" @@ -29,6 +30,19 @@ func (b *Block) Serialize() []byte { return result.Bytes() } +// 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.GetHash()) + } + txHash = sha256.Sum256(bytes.Join(txHashes, []byte{})) + + return txHash[:] +} + // NewBlock creates and returns Block func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block { block := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0} diff --git a/proofofwork.go b/proofofwork.go index 05de09b..fe55525 100644 --- a/proofofwork.go +++ b/proofofwork.go @@ -31,18 +31,10 @@ func NewProofOfWork(b *Block) *ProofOfWork { } func (pow *ProofOfWork) prepareData(nonce int) []byte { - var txHashes [][]byte - var txHash [32]byte - - for _, tx := range pow.block.Transactions { - txHashes = append(txHashes, tx.GetHash()) - } - txHash = sha256.Sum256(bytes.Join(txHashes, []byte{})) - data := bytes.Join( [][]byte{ pow.block.PrevBlockHash, - txHash[:], + pow.block.HashTransactions(), IntToHex(pow.block.Timestamp), IntToHex(int64(targetBits)), IntToHex(int64(nonce)), @@ -59,7 +51,7 @@ func (pow *ProofOfWork) Run() (int, []byte) { var hash [32]byte nonce := 0 - fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data) + fmt.Printf("Mining a new block") for nonce < maxNonce { data := pow.prepareData(nonce)