您好,登錄后才能下訂單哦!
本篇文章為大家展示了Go實現原理的示例分析,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
前言:
簡單原理代碼描述
core: 塊、 區塊實現 main: example 運行
BlockMain 執行目錄:
package main import "Chains/core" func main() { sc := core.NewBlockChain() sc.SendData("send 1 btc to jacky") sc.SendData("send 1 eos to jack") sc.Print() }
Block 區塊:
package core import ( "crypto/sha256" "encoding/hex" "time" ) type Block struct { Index int64 //區塊編號 Timestamp int64 //區塊時間戳 PreBlockHash string //上一個區哈希值 Hash string //當前區塊哈希值 Data string //區塊數據 } func calculateHash(b Block) string{ blockData := string(b.Index) + string(b.Timestamp) + b.PreBlockHash hashInBytes := sha256.Sum256([]byte(blockData)) return hex.EncodeToString(hashInBytes[:]) } func GenerateNewBlock(preBlock Block,data string) Block{ newBlock := Block{} newBlock.Index = preBlock.Index + 1 newBlock.PreBlockHash = preBlock.Hash newBlock.Timestamp = time.Now().Unix() newBlock.Hash = calculateHash(newBlock) return newBlock } func GenerateGenesisBlock() Block { preBlock := Block{} preBlock.Index = 1 preBlock.Hash = "" return GenerateNewBlock(preBlock,"Genesies Block") }
BlockChain 區塊鏈如何實現
package core import ( "log" "fmt" ) type BlockChain struct { Blocks []*Block } func NewBlockChain() *BlockChain { genesisBlock := GenerateGenesisBlock() blockchain := BlockChain{} blockchain.ApendBlock(&genesisBlock) return &blockchain } func (bc *BlockChain) SendData(data string){ preBlock := bc.Blocks[len(bc.Blocks)-1 ] newBlock := GenerateNewBlock(*preBlock,data) bc.ApendBlock(&newBlock) } func (bc *BlockChain) ApendBlock(newBlock *Block){ if len(bc.Blocks) == 0{ bc.Blocks = append(bc.Blocks,newBlock) return } if isValid(*newBlock,*bc.Blocks[len(bc.Blocks)-1]){ bc.Blocks = append(bc.Blocks,newBlock) }else{ log.Fatal("invalid block") } } func (bc *BlockChain) Print(){ for _,block := range bc.Blocks{ fmt.Printf("Index:%d\n",block.Index) fmt.Printf("Pre.Hash:%s\n",block.PreBlockHash) fmt.Printf("Curr.Hash:%s\n",block.Hash) fmt.Printf("Data:%s\n",block.Data) fmt.Printf("TimeStamp:%d\n",block.Timestamp) } } func isValid(newBlock Block,oldBlack Block) bool{ if newBlock.Index - 1 != oldBlack.Index { return false } if newBlock.PreBlockHash != oldBlack.Hash{ return false } if calculateHash(newBlock) != newBlock.Hash{ return false } return true }
上述內容就是Go實現原理的示例分析,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。