2017-08-15 02:29:52 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-08-16 01:07:30 -05:00
|
|
|
"bytes"
|
2017-08-15 02:29:52 -05:00
|
|
|
"crypto/sha256"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Block keeps block headers
|
|
|
|
type Block struct {
|
2017-08-17 01:04:56 -05:00
|
|
|
Timestamp int64
|
|
|
|
Data []byte
|
|
|
|
PrevBlockHash []byte
|
|
|
|
Hash []byte
|
2017-08-15 02:29:52 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetHash calculates and sets block hash
|
|
|
|
func (b *Block) SetHash() {
|
|
|
|
timestamp := []byte(strconv.FormatInt(b.Timestamp, 10))
|
2017-08-17 01:04:56 -05:00
|
|
|
headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})
|
2017-08-16 01:07:30 -05:00
|
|
|
hash := sha256.Sum256(headers)
|
2017-08-15 02:29:52 -05:00
|
|
|
|
2017-08-16 01:07:30 -05:00
|
|
|
b.Hash = hash[:]
|
2017-08-15 02:29:52 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewBlock creates and returns Block
|
|
|
|
func NewBlock(data string, prevBlock []byte) *Block {
|
2017-08-16 01:10:41 -05:00
|
|
|
block := &Block{time.Now().Unix(), []byte(data), prevBlock, []byte{}}
|
2017-08-15 02:29:52 -05:00
|
|
|
block.SetHash()
|
|
|
|
return block
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewGenesisBlock creates and returns genesis Block
|
|
|
|
func NewGenesisBlock() *Block {
|
2017-08-16 02:12:44 -05:00
|
|
|
return NewBlock("Genesis Block", []byte{})
|
2017-08-15 02:29:52 -05:00
|
|
|
}
|