GO语言构建区块链

野性酷女 2022-03-15 00:22 294阅读 0赞

学习爱慕课:https://www.imooc.com/learn/1011
创建第一个区块链项目
在这里插入图片描述
读取区块
在这里插入图片描述
插入一个区块数据
在这里插入图片描述
1.rpc/Server.go

  1. package main
  2. import (
  3. "encoding/json"
  4. "hello/core"
  5. "io"
  6. "net/http"
  7. )
  8. var blockchain *core.Blockchain
  9. func run() {
  10. http.HandleFunc("/blockchain/get",blockchainGetHandLer)
  11. http.HandleFunc("/blockchain/write",blockchainWiiteHandLer)
  12. http.ListenAndServe("localhost:9998",nil)
  13. }
  14. func blockchainGetHandLer(w http.ResponseWriter,r *http.Request) {
  15. bytes,error := json.Marshal(blockchain)
  16. if error != nil {
  17. http.Error(w,error.Error(),http.StatusInternalServerError)
  18. return
  19. }
  20. io.WriteString(w,string(bytes))
  21. }
  22. func blockchainWiiteHandLer(w http.ResponseWriter,r *http.Request) {
  23. blockData := r.URL.Query().Get("data")
  24. blockchain.SendData(blockData)
  25. blockchainGetHandLer(w,r)
  26. }
  27. func main() {
  28. blockchain = core.NewBlockchain()
  29. run()
  30. }

2.core/Blockchain.go

  1. package core
  2. import (
  3. "fmt"
  4. "log"
  5. )
  6. type Blockchain struct {
  7. Blocks []*Block
  8. }
  9. func NewBlockchain()*Blockchain {
  10. genesisBlock := GenerateGenesisBlock()
  11. blockchain := Blockchain{}
  12. blockchain.ApendBlock(&genesisBlock)
  13. return &blockchain
  14. }
  15. func (bc *Blockchain)SendData(data string) {
  16. preBlock := bc.Blocks[len(bc.Blocks) - 1]
  17. newBlock := GenerateNewBlock(*preBlock,data)
  18. bc.ApendBlock(&newBlock)
  19. }
  20. func (bc *Blockchain)ApendBlock(newBlock *Block) {
  21. if len(bc.Blocks) == 0 {
  22. bc.Blocks = append(bc.Blocks,newBlock)
  23. return
  24. }
  25. if isValid(*newBlock,*bc.Blocks[len(bc.Blocks) -1 ]) {
  26. bc.Blocks = append(bc.Blocks, newBlock)
  27. }else {
  28. log.Fatal("invalid blick")
  29. }
  30. }
  31. func (bc *Blockchain) Print() {
  32. for _, block := range bc.Blocks{
  33. fmt.Printf("index: %d\n",block.Index)
  34. fmt.Printf("prev.hash: %s\n",block.PrevBlockHash)
  35. fmt.Printf("curr.hash: %s\n",block.Hash)
  36. fmt.Printf("data: %s\n",block.Date)
  37. fmt.Printf("timestamp: %d\n",block.Timestamp)
  38. fmt.Println()
  39. }
  40. }
  41. func isValid(newBlock Block,oldBlock Block) bool {
  42. if newBlock.Index -1 != oldBlock.Index{
  43. return false
  44. }
  45. if newBlock.PrevBlockHash != oldBlock.Hash {
  46. return false
  47. }
  48. if calculateHash(newBlock) != newBlock.Hash {
  49. return false
  50. }
  51. return true
  52. }

3.core/Block.go

  1. package core
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "time"
  6. )
  7. //区块结构图
  8. type Block struct {
  9. Index int64 //区块编号
  10. Timestamp int64 //区块时间错
  11. PrevBlockHash string //当前区块哈希值
  12. Hash string //当前区块hash
  13. Date string //区块数据
  14. }
  15. func calculateHash(b Block) string {
  16. blockData := string(b.Index)+string(b.Timestamp)+b.PrevBlockHash+b.Date
  17. hashInBytes := sha256.Sum256([]byte(blockData))
  18. return hex.EncodeToString(hashInBytes[:])
  19. }
  20. func GenerateNewBlock(preBlock Block,data string) Block {
  21. newBlock := Block{}
  22. newBlock.Index = preBlock.Index + 1
  23. newBlock.PrevBlockHash = preBlock.Hash
  24. newBlock.Timestamp = time.Now().Unix()
  25. newBlock.Date = data
  26. newBlock.Hash = calculateHash(newBlock)
  27. return newBlock
  28. }
  29. func GenerateGenesisBlock() Block {
  30. preBlock := Block{}
  31. preBlock.Index = -1
  32. preBlock.Hash = ""
  33. return GenerateNewBlock(preBlock,"Genesis Block")
  34. }

4.cmd/main.go

  1. package main
  2. import (
  3. "hello/core"
  4. )
  5. func main() {
  6. bc := core.NewBlockchain()
  7. bc.SendData("send 1 BTC to Jacky")
  8. bc.SendData("send 1 EOS to Jack")
  9. bc.Print()
  10. }

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读