赞
踩
前言:
简单原理代码描述
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
- }

后续补充优化~~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。