GO语言构建区块链
学习爱慕课:https://www.imooc.com/learn/1011
创建第一个区块链项目
读取区块
插入一个区块数据
1.rpc/Server.go
package main
import (
"encoding/json"
"hello/core"
"io"
"net/http"
)
var blockchain *core.Blockchain
func run() {
http.HandleFunc("/blockchain/get",blockchainGetHandLer)
http.HandleFunc("/blockchain/write",blockchainWiiteHandLer)
http.ListenAndServe("localhost:9998",nil)
}
func blockchainGetHandLer(w http.ResponseWriter,r *http.Request) {
bytes,error := json.Marshal(blockchain)
if error != nil {
http.Error(w,error.Error(),http.StatusInternalServerError)
return
}
io.WriteString(w,string(bytes))
}
func blockchainWiiteHandLer(w http.ResponseWriter,r *http.Request) {
blockData := r.URL.Query().Get("data")
blockchain.SendData(blockData)
blockchainGetHandLer(w,r)
}
func main() {
blockchain = core.NewBlockchain()
run()
}
2.core/Blockchain.go
package core
import (
"fmt"
"log"
)
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 blick")
}
}
func (bc *Blockchain) Print() {
for _, block := range bc.Blocks{
fmt.Printf("index: %d\n",block.Index)
fmt.Printf("prev.hash: %s\n",block.PrevBlockHash)
fmt.Printf("curr.hash: %s\n",block.Hash)
fmt.Printf("data: %s\n",block.Date)
fmt.Printf("timestamp: %d\n",block.Timestamp)
fmt.Println()
}
}
func isValid(newBlock Block,oldBlock Block) bool {
if newBlock.Index -1 != oldBlock.Index{
return false
}
if newBlock.PrevBlockHash != oldBlock.Hash {
return false
}
if calculateHash(newBlock) != newBlock.Hash {
return false
}
return true
}
3.core/Block.go
package core
import (
"crypto/sha256"
"encoding/hex"
"time"
)
//区块结构图
type Block struct {
Index int64 //区块编号
Timestamp int64 //区块时间错
PrevBlockHash string //当前区块哈希值
Hash string //当前区块hash
Date string //区块数据
}
func calculateHash(b Block) string {
blockData := string(b.Index)+string(b.Timestamp)+b.PrevBlockHash+b.Date
hashInBytes := sha256.Sum256([]byte(blockData))
return hex.EncodeToString(hashInBytes[:])
}
func GenerateNewBlock(preBlock Block,data string) Block {
newBlock := Block{}
newBlock.Index = preBlock.Index + 1
newBlock.PrevBlockHash = preBlock.Hash
newBlock.Timestamp = time.Now().Unix()
newBlock.Date = data
newBlock.Hash = calculateHash(newBlock)
return newBlock
}
func GenerateGenesisBlock() Block {
preBlock := Block{}
preBlock.Index = -1
preBlock.Hash = ""
return GenerateNewBlock(preBlock,"Genesis Block")
}
4.cmd/main.go
package main
import (
"hello/core"
)
func main() {
bc := core.NewBlockchain()
bc.SendData("send 1 BTC to Jacky")
bc.SendData("send 1 EOS to Jack")
bc.Print()
}
还没有评论,来说两句吧...