Improve block transactions hashing
This commit is contained in:
parent
08a211be41
commit
206f87e265
14
block.go
14
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}
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
Loading…
Reference in New Issue