-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
100 lines (83 loc) · 2.01 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
package main
import (
"flag"
"fmt"
"os"
)
type CLI struct{}
func (c *CLI) list() {
bc := NewBlockchain()
defer bc.db.Close()
bc.List()
}
func (c *CLI) createBlockchain(address string) {
bc := CreateBlockchain(address)
bc.db.Close()
}
func (c *CLI) send(value uint64, from, to string) {
bc := NewBlockchain()
defer bc.db.Close()
tx := bc.Send(value, from, to)
bc.AddBlock([]*Transaction{tx})
}
func (c *CLI) getBalance(address string) uint64 {
bc := NewBlockchain()
defer bc.db.Close()
return bc.GetBalance(address)
}
func (c *CLI) newWallet() string {
return NewKeyStore().CreateWallet().GetAddress()
}
func (c *CLI) Run() {
newCmd := flag.NewFlagSet("new", flag.ExitOnError)
listCmd := flag.NewFlagSet("list", flag.ExitOnError)
sendCmd := flag.NewFlagSet("send", flag.ExitOnError)
getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError)
newWalletCmd := flag.NewFlagSet("newwallet", flag.ExitOnError)
newAddress := newCmd.String("address", "", "")
sendValue := sendCmd.Uint64("value", 0, "")
sendFrom := sendCmd.String("from", "", "")
sendTo := sendCmd.String("to", "", "")
getBalanceAddress := getBalanceCmd.String("address", "", "")
switch os.Args[1] {
case "new":
newCmd.Parse(os.Args[2:])
case "send":
sendCmd.Parse(os.Args[2:])
case "getbalance":
getBalanceCmd.Parse(os.Args[2:])
case "newwallet":
newWalletCmd.Parse(os.Args[2:])
case "list":
listCmd.Parse(os.Args[2:])
default:
os.Exit(1)
}
if newCmd.Parsed() {
if *newAddress == "" {
newCmd.Usage()
os.Exit(1)
}
c.createBlockchain(*newAddress)
}
if sendCmd.Parsed() {
if *sendValue == 0 || *sendFrom == "" || *sendTo == "" {
sendCmd.Usage()
os.Exit(1)
}
c.send(*sendValue, *sendFrom, *sendTo)
}
if getBalanceCmd.Parsed() {
if *getBalanceAddress == "" {
getBalanceCmd.Usage()
os.Exit(1)
}
fmt.Printf("Balance of '%s': %d\n", *getBalanceAddress, c.getBalance(*getBalanceAddress))
}
if newWalletCmd.Parsed() {
fmt.Printf("Address: %s", c.newWallet())
}
if listCmd.Parsed() {
c.list()
}
}