go公鏈實戰0x00區塊鏈基礎結構

來源:互聯網
上載者:User

墮落了一段時間,終於又找回了學習的動力,滿血歸來。。。

我們知道在如火如荼的區塊鏈應用紅海,goLang越來越多地發揮著不可替代的作用。一方面取決於其文法的簡單性,一方面其具備C++高效處理的特性。今天,我們就用go語言開始構建一個簡單但是具備區塊鏈完整功能的公鏈項目。

由於之前已經用Python構建過簡單的區塊鏈結構,所以對區塊基本結構的東西不再做詳細贅述。

廢話少說上乾貨

區塊Block

Block

type Block struct {    //1.區塊高度    Height int64    //2.上一個區塊HAsh    PrevBlockHash []byte    //3.交易資料    Data []byte    //4.時間戳記    Timestamp int64    //5.Hash    Hash []byte}

設定當前區塊Hash

func (block *Block) SetHash() {    //1.將高度,時間戳記轉換為位元組數組    //base:2  二進位形式    heightBytes := IntToHex(block.Height)    timeStampStr := strconv.FormatInt(block.Timestamp, 2)    timeStamp := []byte(timeStampStr)    //fmt.Println(heightBytes)    //fmt.Println(timeStampStr)    //fmt.Println(timeStamp)    //2.拼接所有屬性    blockBytes := bytes.Join([][]byte{        heightBytes,        block.PrevBlockHash,        block.Data,        timeStamp,        block.Hash}, []byte{})    //fmt.Println(blockBytes)    //3.將拼接後的位元組數群組轉換為Hash值    hash := sha256.Sum256(blockBytes)    fmt.Println(hash)    block.Hash = hash[:]    //fmt.Println(block.Hash)}

建立新區快

func NewBlock(data string, height int64, prevBlockHash []byte) *Block {    //建立區塊    block := &Block{        Height:        height,        PrevBlockHash: prevBlockHash,        Data:          []byte(data),        Timestamp:     time.Now().Unix(),        Hash:          nil}    //設定HAsh值    block.SetHash()    return block}

創世區塊建立

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})}

區塊鏈BlockChain

區塊鏈

type Blockchain struct {    //有序區塊的數組    Blocks [] *Block}

建立帶有創世區塊的區塊鏈

func CreateBlockchainWithGensisBlock() *Blockchain  {    gensisBlock := CreateGenesisBlock("Gensis Block...")    return &Blockchain{[] *Block{gensisBlock}}}

新增一個區塊到區塊鏈

func (blc *Blockchain) AddBlockToBlockchain(data string, height int64, prevHash []byte)  {    //建立區塊    newBlock := NewBlock(data, height, prevHash)    //上鏈    blc.Blocks = append(blc.Blocks, newBlock)}

utils協助工具輔助(int64轉化為byte數組)

import (    "bytes"    "encoding/binary"    "log")//將int64轉換為bytesfunc IntToHex(num int64) []byte  {    buff := new(bytes.Buffer)    err := binary.Write(buff, binary.BigEndian, num)    if err != nil {        log.Panic(err)    }    return buff.Bytes()}

測試Demo

/**@author: chaors@file:   main.go@time:   2018/06/21 22:01@desc:   區塊資訊的樣本*/package mainimport (    "chaors.com/LearnGo/publicChaorsChain/part1-Basic-Prototype/BLC"    "fmt")func main() {    //genesisBlock := BLC.CreateGenesisBlock("Genenis Block")    //建立帶有創世區塊的區塊鏈    blockchain := BLC.CreateBlockchainWithGensisBlock()    //添加一個新區快    blockchain.AddBlockToBlockchain("first Block",        blockchain.Blocks[len(blockchain.Blocks)-1].Height,        blockchain.Blocks[len(blockchain.Blocks)-1].Hash)    blockchain.AddBlockToBlockchain("second Block",        blockchain.Blocks[len(blockchain.Blocks)-1].Height,        blockchain.Blocks[len(blockchain.Blocks)-1].Hash)    blockchain.AddBlockToBlockchain("third Block",        blockchain.Blocks[len(blockchain.Blocks)-1].Height,        blockchain.Blocks[len(blockchain.Blocks)-1].Hash)    fmt.Println(blockchain)}

運行結果

我們看到啟動並執行結果,列印的內容為包含創世區塊在內的四個區塊的區塊鏈。

image.png

.
.
.
.

互連網顛覆世界,區塊鏈顛覆互連網!

-------------------------------------------------20180622 20:35

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.