1. 程式人生 > 實用技巧 >區塊鏈V3版本實現之六

區塊鏈V3版本實現之六

命令列demo程式碼:

 1 package main
 2 
 3 import (
 4    "fmt"
 5    "os"
 6 )
 7 
 8 func main()  {
 9    //返回的是陣列
10    cmds := os.Args
11 
12    //通過字元比較,去選擇執行相應的程式
13    for i, cmd := range cmds{
14       fmt.Printf("cmd[%d] : %s\n", i, cmd)
15    }
16 }

顯示效果:

使用命令列分析:

  1. 所有的支配動作交給命令列來做
  2. 主函式只需要呼叫命令列結構即可
  3. 根據輸入的不同命令,命令列做相應動作

    a) addBlock

    b) printChain

CLI:command line的縮寫

type CLI struct{

  bc*BlockChain

}

新增區塊的時候:bc.addBlock(data),data通過os.Args拿回來

列印區塊鏈時候:遍歷區塊鏈,不需要外部輸入資料

部分程式碼(cli.go檔案中命令列的實現):

 1 package main
 2 
 3 import (
 4    "fmt"
 5    "os"
 6 )
 7 
 8 const Usage = `
 9    ./blockchain addBlock "xxxxxx
" 新增資料到區塊鏈 10 ./blockchain printChain 列印區塊鏈 11 ` 12 13 type CLI struct { 14 bc *BlockChain 15 } 16 17 //給CLI提供一個方法,進行命令解析,從而執行排程 18 func (cli *CLI) Run() { 19 20 cmds := os.Args 21 22 if len(cmds) < 2 { 23 fmt.Printf(Usage) 24 os.Exit(1) 25 } 26 27 switch cmds[1
] { 28 case "addBlock": 29 if len(cmds) != 3 { 30 fmt.Printf(Usage) 31 os.Exit(1) 32 } 33 34 fmt.Printf("新增區塊命令被呼叫, 資料:%s\n", cmds[2]) 35 36 data := cmds[2] 37 cli.AddBlock(data) 38 39 case "printChain": 40 fmt.Printf("列印區塊鏈命令被呼叫\n") 41 cli.PrintChain() 42 43 default: 44 fmt.Printf("無效的命令,請檢查\n") 45 fmt.Printf(Usage) 46 } 47 //新增區塊的時候: bc.addBlock(data), data 通過os.Args拿回來 48 //列印區塊鏈時候:遍歷區塊鏈,不需要外部輸入資料 49 }

部分程式碼(commands.go的相關命令實現):

 1 package main
 2 
 3 import (
 4    "fmt"
 5    "time"
 6    "bytes"
 7 )
 8 
 9 //實現具體的命令
10 
11 func (cli *CLI) AddBlock(data string) {
12    cli.bc.AddBlock(data)
13    fmt.Printf("新增區塊成功!\n")
14 }
15 
16 func (cli *CLI) PrintChain() {
17 
18    it := cli.bc.NewIterator()
19 
20    for {
21       block := it.Next()
22       fmt.Printf("++++++++++++++++++++++++++++++++\n")
23 
24       fmt.Printf("Version : %d\n", block.Version)
25       fmt.Printf("PrevBlockHash : %x\n", block.PrevBlockHash)
26       fmt.Printf("MerKleRoot : %x\n", block.MerKleRoot)
27 
28       timeFormat := time.Unix(int64(block.TimeStamp), 0).Format("2006-01-02 15:04:05")
29       fmt.Printf("TimeStamp : %s\n", timeFormat)
30 
31       fmt.Printf("Difficulity : %d\n", block.Difficulity)
32       fmt.Printf("Nonce : %d\n", block.Nonce)
33       fmt.Printf("Hash : %x\n", block.Hash)
34       fmt.Printf("Data : %s\n", block.Data)
35 
36       pow := NewProofOfWork(block)
37       fmt.Printf("IsValid: %v\n", pow.IsValid())
38 
39       if bytes.Equal(block.PrevBlockHash, []byte{}) {
40          fmt.Printf("區塊鏈遍歷結束!\n")
41          break
42       }
43    }
44 }

部分程式碼(main.go檔案的改寫):

package main

func main() {

   bc := NewBlockChain()
   defer bc.db.Close()
   cli := CLI{bc}
   cli.Run()
}

執行指令碼(方便執行):

1 #!/bin/bash
2 rm blockchain
3 rm *.db
4 
5 go build -o blockchain *.go
6 ./blockchain

顯示效果:

V3版本專案目錄結構:

本人的系統是windows10,不能用命令列執行,如果有大佬知道如何執行,請指點一下,謝謝!