一. 代码结构
Block.go :定义区块结构与方法
BlockChain.go :定义区块链结构与方法
help.go :将常用代码块进行封装,形成帮助库
main.go:测试代码
二.定义区块结构与方法
package BLC import ( "time" "strconv" "bytes" "crypto/sha256" ) //定义区块 type Block struct { //1.区块高度,也就是区块的编号,第几个区块 Height int64 //2.上一个区块的Hash值 PreBlockHash []byte //3.交易数据(最终都属于transaction 事务) Data []byte //4.创建时间的时间戳 TimeStamp int64 //5.当前区块的Hash值 Hash []byte //6.Nonce 随机数,用于验证工作量证明 Nonce int64 } //定义区块生成Hash的方法 func (block *Block) SetHash() { //1.将Height 转换为字节数组 []byte heightBytes := IntToHex(block.Height) //2.将TimeStamp 转换为字节数组 []byte //2.1 将Int64的TimeStamp 转换成二进制 timeString := strconv.FormatInt(block.TimeStamp, 2) //2.2 将二进制字符串转成字节数组 timeBytes := []byte(timeString) //3.拼接所有属性,形成一个二维的byte数组 blockBytes := bytes.Join([][]byte{heightBytes, block.PreBlockHash, block.Data, timeBytes, block.Hash}, []byte{}) //4.生成Hash hash := sha256.Sum256(blockBytes) block.Hash = hash[:] } //1. 创建新的区块 func NewBlock(data string, height int64, PreBlockHash []byte) *Block { //创建区块 block := &Block{ height, PreBlockHash, []byte(data), time.Now().Unix(), nil, 0, } //设置Hash block.SetHash() return block } //2.生成创世区块 func CreateGenesisBlock(data string) *Block { return NewBlock(data, 1, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) }
三.定义区块链与方法
package BLC type BlockChain struct { Blocks []*Block //存储有序的区块 } func (blc *BlockChain)AddBlockChain(data string,height int64,preHash []byte){ //创建新区块 newBlock := NewBlock(data,height,preHash) //往链中添加区块 blc.Blocks=append(blc.Blocks,newBlock) } //1.创建带有创世区块的区块链 func CreateBlockChainWithGenesisBlock() *BlockChain { //创建创世区块 genesisBlock := CreateGenesisBlock("Genesis Data..") //返回区块链对象 return &BlockChain{[]*Block{genesisBlock}} }
四.帮助代码库
package BLC import ( "bytes" "encoding/binary" "log" ) //将int64转换为字节数组 func IntToHex(num int64) []byte { buff := new(bytes.Buffer) err := binary.Write(buff, binary.BigEndian, num) if err != nil { log.Panic(err) } return buff.Bytes() }
五.测试代码
package main import ( "publicChain/BLC" "fmt" ) func main() { //创建创世区块 blockChain := BLC.CreateBlockChainWithGenesisBlock() //创建新的区块 blockChain.AddBlockChain("Send $100 to Bruce", blockChain.Blocks[len(blockChain.Blocks)-1].Height+1, blockChain.Blocks[len(blockChain.Blocks)-1].Hash) blockChain.AddBlockChain("Send $200 to Apple", blockChain.Blocks[len(blockChain.Blocks)-1].Height+1, blockChain.Blocks[len(blockChain.Blocks)-1].Hash) blockChain.AddBlockChain("Send $300 to Alice", blockChain.Blocks[len(blockChain.Blocks)-1].Height+1, blockChain.Blocks[len(blockChain.Blocks)-1].Hash) blockChain.AddBlockChain("Send $400 to Bob", blockChain.Blocks[len(blockChain.Blocks)-1].Height+1, blockChain.Blocks[len(blockChain.Blocks)-1].Hash) fmt.Printf("创建的区块链为:\t%v\n", blockChain) fmt.Printf("区块链存储的区块为:\t%v\n", blockChain.Blocks) fmt.Printf("第二个区块的数据信息(交易信息)为:\t%v\n", string(blockChain.Blocks[1].Data)) }
六.结果显示
有疑问加站长微信联系(非本文作者)