-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCLI.go
131 lines (114 loc) · 2.4 KB
/
CLI.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
@author:BOEN
@data:2022/8/21
@note:
**/
package main
import (
"flag"
"fmt"
"github.com/go-kit/kit/log"
"os"
"strconv"
)
type CLI struct {
bc *Blockchain
}
/**
* @Title printUsage
* @Description //打印命令行交互信息
* @Author Cofeesy 20:23 2022/8/21
* @Param nil
* @Return nil
**/
func (cli *CLI) printUsage() {
fmt.Println("Usage:")
fmt.Println(" addBlock -data BLOCK_DATA - add a block to the blockchain")
fmt.Println(" printChain - print all the blocks of the blockchain")
}
/**
* @Title validateArgs
* @Description //命令行参数验证
* @Author Cofeesy 20:24 2022/8/21
* @Param nil
* @Return nil
**/
func (cli *CLI) validateArgs() {
if len(os.Args) < 2 {
cli.printUsage()
os.Exit(1)
}
}
/**
* @Title addBlock
* @Description //调用底层函数增加区块
* @Author Cofeesy 18:46 2022/8/21
* @Param data string
* @Return nil
**/
func (cli *CLI) addBlock(data string) {
cli.bc.AddBlock(data)
fmt.Println("Success!")
}
/**
* @Title printChain
* @Description //根据迭代对象打印每个区块的信息
* @Author Cofeesy 19:06 2022/8/21
* @Param nil
* @Return nil
**/
func (cli *CLI) printChain() {
//返回需要打印的Iterator对象
bci := cli.bc.Iterator()
for {
block := bci.Next()
fmt.Printf("Prev. hash: %x\n", block.PrevBlockHash)
fmt.Printf("Data: %s\n", block.Data)
fmt.Printf("Hash: %x\n", block.Hash)
pow := NewProofOfWork(block)
fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.isValid()))
fmt.Println()
if len(block.PrevBlockHash) == 0 {
break
}
}
}
/**
* @Title Run
* @Description //解析命令行参数
* @Author Cofeesy 18:21 2022/8/21
* @Param nil
* @Return nil
**/
func (cli *CLI) Run() {
logger := log.NewLogfmtLogger(os.Stdout)
cli.validateArgs()
addBlockCmd := flag.NewFlagSet("addBlock", flag.ExitOnError)
printChainCmd := flag.NewFlagSet("printChain", flag.ExitOnError)
addBlockData := addBlockCmd.String("data", "", "Block data")
switch os.Args[1] {
case "addBlock":
err := addBlockCmd.Parse(os.Args[2:])
if err != nil {
logger.Log("addBlockCmd", err)
}
case "printChain":
err := printChainCmd.Parse(os.Args[2:])
if err != nil {
logger.Log("printChainCmd", err)
}
default:
cli.printUsage()
os.Exit(1)
}
if addBlockCmd.Parsed() {
if *addBlockData == "" {
addBlockCmd.Usage()
os.Exit(1)
}
cli.addBlock(*addBlockData)
}
if printChainCmd.Parsed() {
cli.printChain()
}
}