blockchain_go/block.go

40 lines
819 B
Go
Raw Normal View History

package main
import (
2017-08-16 01:07:30 -05:00
"bytes"
"crypto/sha256"
2017-08-16 01:07:30 -05:00
"fmt"
"strconv"
"time"
)
// Block keeps block headers
type Block struct {
Timestamp int64
Data []byte
PrevBlock []byte
2017-08-16 00:33:15 -05:00
Hash []byte
}
// SetHash calculates and sets block hash
func (b *Block) SetHash() {
timestamp := []byte(strconv.FormatInt(b.Timestamp, 10))
2017-08-16 01:07:30 -05:00
headers := bytes.Join([][]byte{b.PrevBlock, b.Data, timestamp}, []byte{})
fmt.Printf("%s\n", headers)
hash := sha256.Sum256(headers)
2017-08-16 01:07:30 -05:00
b.Hash = hash[:]
}
// NewBlock creates and returns Block
func NewBlock(data string, prevBlock []byte) *Block {
block := &Block{time.Now().Unix(), []byte(data), prevBlock, []byte("")}
block.SetHash()
return block
}
// NewGenesisBlock creates and returns genesis Block
func NewGenesisBlock() *Block {
return NewBlock("Genesis Block", []byte("0"))
}