Go实现原理的示例分析
本篇文章为大家展示了Go实现原理的示例分析,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
从事西部信息中心,服务器租用,云主机,网页空间,国际域名空间,CDN,网络代维等服务。
前言:
简单原理代码描述
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实现原理的示例分析,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。
当前文章:Go实现原理的示例分析
路径分享:http://myzitong.com/article/gdhdjg.html