1 Star 0 Fork 0

叶明志 / golang练习

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
block.go 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
yemingzhi 提交于 2020-03-17 16:11 . add
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))
headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})
hash := sha256.Sum256(headers)
b.Hash = hash[:]
}
func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{
time.Now().Unix(),
[]byte(data),
prevBlockHash,
[]byte{},
}
block.SetHash()
return block
}
type Blockchain struct {
blocks []*Block
}
func (bc *Blockchain) AddBlock(data string) {
prevBlock := bc.blocks[len(bc.blocks)-1]
newBlock := NewBlock(data, prevBlock.Hash)
bc.blocks = append(bc.blocks, newBlock)
}
func NewGenesisBlock() *Block {
return NewBlock("Genesis Block", []byte{})
}
func NewBlockchain() *Blockchain {
return &Blockchain{
[]*Block{NewGenesisBlock()},
}
}
func main() {
bc := NewBlockchain()
bc.AddBlock("Send 1 BTC to Ivan")
bc.AddBlock("Send 2 more BTC to Ivan")
for _, block := range bc.blocks {
fmt.Printf("Prev.hash:%x\n", block.PrevBlockHash)
fmt.Printf("Data:%s\n", block.Data)
fmt.Printf("Hash:%x\n", block.Hash)
fmt.Println()
}
}
Go
1
https://gitee.com/yemingzhi/GolangLearnPractice1.git
git@gitee.com:yemingzhi/GolangLearnPractice1.git
yemingzhi
GolangLearnPractice1
golang练习
2bf136849dce

搜索帮助

53164aa7 5694891 3bd8fe86 5694891