BitCoin全攻略三
单个区块的代码已经差不多了
现在我们要创建多个区块
然后把一个个区块串联起来
形成 区块链
我们先来写一个结构体,表示区块链
然后里面就放的是区块数组
type BlockChain struct{
blocks []*Block
}
然后我们写一个方法去创建区块链
func NewBlockChain() *BlockChain{
bc := BlockChain{
blocks: []*Block{},
}
}
一般我们会在创建整个区块链的时候
同时去创建第一个区块
也就是 创世区块
genesisInfo := []byte("Hello world! Hello blockchain!")
genesisBlock := NewBlock(genesisInfo, []byte{})
然后我们把创世区块加入到区块链中
func NewBlockChain() *BlockChain{
genesisInfo := []byte("Hello world! Hello blockchain!")
genesisBlock := NewBlock(genesisInfo, []byte{})
bc := BlockChain{
blocks: []*Block{genesisBlock},
}
return &bc
}
然后我们来看看完整代码
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() {
blocks := NewBlockChain().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 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[:]
}