区块链原理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

}复制代码


转载于:https://juejin.im/post/5cf5e9a2f265da1bcc192da7

猜你喜欢

转载自blog.csdn.net/weixin_33842328/article/details/91441904