Refactor Block.SetHash

This commit is contained in:
Ivan Kuznetsov 2017-08-16 13:07:30 +07:00
parent 8767cb3528
commit 18fe4a94c9
1 changed files with 6 additions and 11 deletions

View File

@ -1,8 +1,9 @@
package main package main
import ( import (
"bytes"
"crypto/sha256" "crypto/sha256"
"log" "fmt"
"strconv" "strconv"
"time" "time"
) )
@ -17,18 +18,12 @@ type Block struct {
// SetHash calculates and sets block hash // SetHash calculates and sets block hash
func (b *Block) SetHash() { func (b *Block) SetHash() {
h := sha256.New()
timestamp := []byte(strconv.FormatInt(b.Timestamp, 10)) timestamp := []byte(strconv.FormatInt(b.Timestamp, 10))
var data []byte headers := bytes.Join([][]byte{b.PrevBlock, b.Data, timestamp}, []byte{})
data = append(data, b.PrevBlock...) fmt.Printf("%s\n", headers)
data = append(data, b.Data...) hash := sha256.Sum256(headers)
data = append(data, timestamp...)
_, err := h.Write(data) b.Hash = hash[:]
if err != nil {
log.Panic(err)
}
b.Hash = h.Sum(nil)
} }
// NewBlock creates and returns Block // NewBlock creates and returns Block