BitCoin全攻略四
我们创建完了区块链
现在我们来写一个方法
往区块链里面添加区块
func (bc *BlockChain) AddBlock(data []byte){
//获取前一个区块
lastBlock := bc.Blocks[len(bc.Blocks) - 1]
//获取前一个区块的hash值
prevHash := lastBlock.Hash
//创建当前区块
newBlock := NewBlock(data, prevHash)
//添加到区块链
bc.Blocks = append(bc.Blocks, newBlock)
}
然后我们看一下完整代码
package main
import (
"crypto/sha256"
"fmt"
)
type Block struct {
//1.前区块哈希值
PrevBlockHash []byte
//2.当前区块的哈希
Hash []byte
//3.数据
Data []byte
}
type BlockChain struct {
Blocks []*Block
}
func main() {
blockchain := NewBlockChain()
blockchain.AddBlock([]byte("I am Alice"))
blockchain.AddBlock([]byte("I am Bob"))
blockchain.AddBlock([]byte("I am Mike"))
blockchain.AddBlock([]byte("I am Andy"))
blocks := blockchain.Blocks
for i, block := range blocks {
fmt.Println("========== 当前区块 ", i, "==========")
fmt.Printf("前一区块的hash值为: %x\n", block.PrevBlockHash)
fmt.Printf("当前区块的hash值为: %x\n", block.Hash)
fmt.Printf("当前区块的data为: %s\n", block.Data)
}
}
func (bc *BlockChain) AddBlock(data []byte) {
//获取前一个区块
lastBlock := bc.Blocks[len(bc.Blocks)-1]
//获取前一个区块的hash值
prevHash := lastBlock.Hash
//创建当前区块
newBlock := NewBlock(data, prevHash)
//添加到区块链
bc.Blocks = append(bc.Blocks, newBlock)
}
func NewBlockChain() *BlockChain {
genesisInfo := []byte("Hello world! Hello blockchain!")
genesisBlock := NewBlock(genesisInfo, []byte{})
bc := BlockChain{
Blocks: []*Block{genesisBlock},
}
return &bc
}
func NewBlock(data []byte, prevBlockHash []byte) *Block {
block := Block{
PrevBlockHash: prevBlockHash,
Hash: nil,
Data: data,
}
hash := getHash(&block)
block.Hash = hash
return &block
}
func getHash(block *Block) []byte {
var info []byte
info = append(info, block.PrevBlockHash...)
info = append(info, block.Data...)
hash := sha256.Sum256(info)
return hash[:]
}
然后我们看下输出结果
========== 当前区块 0 ==========
前一区块的hash值为:
当前区块的hash值为: 93a26c42840ed836279f3b703386d14649c0052feb3ba5ac1796061f81898aec
当前区块的data为: Hello world! Hello blockchain!
========== 当前区块 1 ==========
前一区块的hash值为: 93a26c42840ed836279f3b703386d14649c0052feb3ba5ac1796061f81898aec
当前区块的hash值为: af3ddf737847a34a42faadf2f39546e1a6966cc856610f13d57ab32954b797c2
当前区块的data为: I am Alice
========== 当前区块 2 ==========
前一区块的hash值为: af3ddf737847a34a42faadf2f39546e1a6966cc856610f13d57ab32954b797c2
当前区块的hash值为: 4aadccb1b8527dbd4dab81039fb243a9421e2346df6df975ffab98da501cc03d
当前区块的data为: I am Bob
========== 当前区块 3 ==========
前一区块的hash值为: 4aadccb1b8527dbd4dab81039fb243a9421e2346df6df975ffab98da501cc03d
当前区块的hash值为: 13fb213a47048fa2f643b22e55f85f6dc97fb99dabd8fbaabe46fad13357c09c
当前区块的data为: I am Mike
========== 当前区块 4 ==========
前一区块的hash值为: 13fb213a47048fa2f643b22e55f85f6dc97fb99dabd8fbaabe46fad13357c09c
当前区块的hash值为: c5fed60d59e5fa4c5a867c8516adf6ce5c23dbef5176d10f0ca87f07db14fd9b
当前区块的data为: I am Andy
我们发现hash值的指向都没问题