一. 代碼結構
Block.go :定義區塊結構與方法
BlockChain.go :定義區塊鏈結構與方法
help.go :將常用代碼塊進行封裝,形成協助庫
main.go:測試代碼
二.定義區塊結構與方法
package BLCimport ( "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 BLCtype 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 BLCimport ( "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 mainimport ( "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))}
六.結果顯示