前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、区块链简单实现
package Block
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"
)
type Block struct{
PreHash string
HashCode string
TimeStamp string
Diff int
Data string
Index int
Nonce int
}
func GenerateFirstBlock(data string) Block {
var firstblock Block
firstblock.PreHash = "0"
firstblock.TimeStamp = time.Now().String()
firstblock.Diff = 4
firstblock.Data = data
firstblock.Index = 1
firstblock.Nonce = 0
firstblock.HashCode = GenerationHashValue(firstblock)
return firstblock
}
func GenerationHashValue(block Block) string{
var hashdata = strconv.Itoa(block.Nonce)+strconv.Itoa(block.Diff)+strconv.Itoa(block.Index)+block.TimeStamp
var sha = sha256.New()
sha.Write([]byte(hashdata))
hashed := sha.Sum(nil)
return hex.EncodeToString(hashed)
}
func GenerationNextBlock(data string,oldBlock Block) Block {
var newBlock Block
newBlock.TimeStamp = time.Now().String()
newBlock.Diff = 4
newBlock.Index = 2
newBlock.Data = data
newBlock.PreHash = oldBlock.HashCode
newBlock.Nonce = 0
newBlock.HashCode = pow(newBlock.Diff,&newBlock)
return newBlock
}
func pow(diff int,block *Block) string{
for{
hash := GenerationHashValue(*block)
fmt.Println(hash)
if strings.HasPrefix(hash, strings.Repeat("0", diff)){
//挖矿成功
fmt.Println("挖矿成功")
return hash
} else {
//没挖到
//随机值自增
block.Nonce++
}
}
}
package Blockchain
import (
"demo2/Block"
"fmt"
)
type Node struct {
NextNode *Node
Data *Block.Block
}
func CreateHeaderNode(data *Block.Block) *Node {
var headerNode = new(Node)
headerNode.NextNode = nil
headerNode.Data=data
return headerNode
}
func AddNode(data *Block.Block,node *Node) *Node{
var newNode = new(Node)
newNode.NextNode=nil
newNode.Data=data
node.NextNode = newNode
return newNode
}
func ShowNodes(node *Node){
n := node
for{
if n.NextNode == nil{
fmt.Println(n.Data)
break
}else{
fmt.Println(n.Data)
n = n.NextNode
}
}
}