区块链V1版本实现之五
阅读原文时间:2023年07月08日阅读:2

代码重构:

block.go文件:

package main

import (
"crypto/sha256"
)

//定义区块结构
type Block struct {
//前区块哈希
PrevBlockHash [] byte
//当前区块哈希
Hash [] byte
//数据,目前使用字节流,v4开始使用交易代替
Data [] byte
}

const genesisInfo = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"

//创建区块,对Block的每一个字段填充数据
func NewBlock(data string, prevBlockHash []byte) *Block{
block := Block{
PrevBlockHash: prevBlockHash,
Hash: []byte{}, //先填充为空
Data: []byte(data),
}

//V1之二版本添加实现hash输出
block.SetHash()

return &block
}

//为了生成区块哈希,实现一个简单的函数,来计算哈希值,没有随机值,没有难度值
func (block *Block) SetHash() {
var data []byte
data = append(data, block.PrevBlockHash…)
data = append(data, block.Data…)

hash /* [32]byte */:= sha256.Sum256(data)
block.Hash = hash[:]
}

blockchain.go文件:

package main

//创建区块链,使用Block数组模拟
type BlockChain struct {
Blocks []*Block
}

//实现创建区块链的方法
func NewBlockChain() *BlockChain {
//在创建的时候添加一个区块:创世块
genesisBlock := NewBlock(genesisInfo, []byte{0x0000000000000000})

bc := BlockChain{Blocks: []*Block{genesisBlock}}
return &bc
}

//添加区块
func (bc *BlockChain) AddBlock(data string) {

//创建一个区块
//bc.Block的最后一个区块的Hash值就是当前新区块的PrevBlockHash
lastBlock := bc.Blocks[len(bc.Blocks) - 1]
prevHash := lastBlock.Hash

block := NewBlock(data, prevHash)

//添加到bc.Block数组中
bc.Blocks = append(bc.Blocks, block)

}

main.go文件:

package main

import (
"fmt"
)

func main() {
fmt.Printf("HelloWorld!!!\n")

////区块实例化
//block := NewBlock(genesisInfo,[]byte{0x0000000000000000})
bc := NewBlockChain()
bc.AddBlock("哈哈哈哈哈")

for i, block := range bc.Blocks{
//区块打印
fmt.Printf("++++++++++++++ %d ++++++++++++++++\n",i)
fmt.Printf("PrevBlockHash : %x\n", block.PrevBlockHash)
fmt.Printf("Hash : %x\n", block.Hash)
fmt.Printf("Data : %s\n", block.Data)
}
}

显示效果: