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 (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/gob"
|
"encoding/gob"
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
@ -29,6 +30,19 @@ func (b *Block) Serialize() []byte {
|
||||||
return result.Bytes()
|
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
|
// NewBlock creates and returns Block
|
||||||
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
|
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
|
||||||
block := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0}
|
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 {
|
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(
|
data := bytes.Join(
|
||||||
[][]byte{
|
[][]byte{
|
||||||
pow.block.PrevBlockHash,
|
pow.block.PrevBlockHash,
|
||||||
txHash[:],
|
pow.block.HashTransactions(),
|
||||||
IntToHex(pow.block.Timestamp),
|
IntToHex(pow.block.Timestamp),
|
||||||
IntToHex(int64(targetBits)),
|
IntToHex(int64(targetBits)),
|
||||||
IntToHex(int64(nonce)),
|
IntToHex(int64(nonce)),
|
||||||
|
@ -59,7 +51,7 @@ func (pow *ProofOfWork) Run() (int, []byte) {
|
||||||
var hash [32]byte
|
var hash [32]byte
|
||||||
nonce := 0
|
nonce := 0
|
||||||
|
|
||||||
fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data)
|
fmt.Printf("Mining a new block")
|
||||||
for nonce < maxNonce {
|
for nonce < maxNonce {
|
||||||
data := pow.prepareData(nonce)
|
data := pow.prepareData(nonce)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue