package main
import (
"bytes"
"crypto/sha256"
"fmt"
"strconv"
"time"
)
type Block struct {
Timestamp int64
Data []byte
PrevBlockHash []byte
Hash []byte
}
func (b *Block) SetHash() {
timestamp := []byte(strconv.FormatInt(b.Timestamp, 10))
fmt.Println(timestamp)
header := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})
fmt.Println("header:", header)
hash := sha256.Sum256(header)
fmt.Println("hash:", hash)
b.Hash = hash[:]
}
func NewBlock(data string, prevBlockHash []byte) *Block {
fmt.Println("正在新增一个区块")
block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}}
block.SetHash()
fmt.Println("Timestamp:", block.Timestamp)
fmt.Println("Data:", block.Data)
fmt.Println("PrevBlockHash:", block.PrevBlockHash)
fmt.Println("Hash:", block.Hash)
return block
}
func NewGenesisBlock() *Block {
fmt.Println("正在生成创世块....请耐心等待")
return NewBlock("这是第一个区块,也叫创世块", []byte{})
}
func main() {
NewGenesisBlock()
NewBlock("hello", []byte{})
}