-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
238 lines (200 loc) · 5.5 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"flag"
"fmt"
"log"
"os"
"strconv"
)
// CLI responsible for processing command line arguments
type CLI struct{}
func (cli *CLI) getBalance(address string) {
if !ValidateAddress(address) {
log.Panic("ERROR: Address is not valid")
}
bc := NewBlockchain()
UTXOSet := UTXOSet{bc}
defer bc.db.Close()
balance := 0
pubKeyHash := Base58Decode([]byte(address))
pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4]
UTXOs := UTXOSet.FindUTXO(pubKeyHash)
for _, out := range UTXOs {
balance += out.Value
}
fmt.Printf("Balance of '%s': %d\n", address, balance)
}
func (cli *CLI) createBlockchain(address string) {
if !ValidateAddress(address) {
log.Panic("ERROR: Address is not valid")
}
bc := CreateBlockchain(address)
defer bc.db.Close()
UTXOSet := UTXOSet{bc}
UTXOSet.Reindex()
fmt.Println("Done!")
}
func (cli *CLI) createWallet() {
wallets, _ := NewWallets()
address := wallets.CreateWallet()
wallets.SaveToFile()
fmt.Printf("Your new address: %s\n", address)
}
func (cli *CLI) listAddresses() {
wallets, err := NewWallets()
if err != nil {
log.Panic(err)
}
addresses := wallets.GetAddresses()
for _, address := range addresses {
fmt.Println(address)
}
}
func (cli *CLI) printChain() {
bc := NewBlockchain()
defer bc.db.Close()
bci := bc.Iterator()
for {
block := bci.Next()
fmt.Printf("============ Block %x ============\n", block.Hash)
fmt.Printf("Prev. block: %x\n", block.PrevBlockHash)
pow := NewProofOfWork(block)
fmt.Printf("PoW: %s\n\n", strconv.FormatBool(pow.Validate()))
for _, tx := range block.Transactions {
fmt.Println(tx)
}
fmt.Printf("\n\n")
if len(block.PrevBlockHash) == 0 {
break
}
}
}
func (cli *CLI) reindexUTXO() {
bc := NewBlockchain()
UTXOSet := UTXOSet{bc}
UTXOSet.Reindex()
count := UTXOSet.CountTransactions()
fmt.Printf("Done! There are %d transactions in the UTXO set.\n", count)
}
func (cli *CLI) send(from, to string, amount int) {
if !ValidateAddress(from) {
log.Panic("ERROR: Sender address is not valid")
}
if !ValidateAddress(to) {
log.Panic("ERROR: Recipient address is not valid")
}
bc := NewBlockchain()
UTXOSet := UTXOSet{bc}
defer bc.db.Close()
tx := NewUTXOTransaction(from, to, amount, &UTXOSet)
cbTx := NewCoinbaseTX(from, "")
txs := []*Transaction{cbTx, tx}
newBlock := bc.MineBlock(txs)
UTXOSet.Update(newBlock)
fmt.Println("Success!")
}
func (cli *CLI) printUsage() {
fmt.Println("Usage:")
fmt.Println(" createblockchain -address ADDRESS - Create a blockchain and send genesis block reward to ADDRESS")
fmt.Println(" createwallet - Generates a new key-pair and saves it into the wallet file")
fmt.Println(" getbalance -address ADDRESS - Get balance of ADDRESS")
fmt.Println(" listaddresses - Lists all addresses from the wallet file")
fmt.Println(" printchain - Print all the blocks of the blockchain")
fmt.Println(" reindexutxo - Rebuilds the UTXO set")
fmt.Println(" send -from FROM -to TO -amount AMOUNT - Send AMOUNT of coins from FROM address to TO")
}
func (cli *CLI) validateArgs() {
if len(os.Args) < 2 {
cli.printUsage()
os.Exit(1)
}
}
// Run parses command line arguments and processes commands
func (cli *CLI) Run() {
cli.validateArgs()
getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError)
createBlockchainCmd := flag.NewFlagSet("createblockchain", flag.ExitOnError)
createWalletCmd := flag.NewFlagSet("createwallet", flag.ExitOnError)
listAddressesCmd := flag.NewFlagSet("listaddresses", flag.ExitOnError)
printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError)
reindexUTXOCmd := flag.NewFlagSet("reindexutxo", flag.ExitOnError)
sendCmd := flag.NewFlagSet("send", flag.ExitOnError)
getBalanceAddress := getBalanceCmd.String("address", "", "The address to get balance for")
createBlockchainAddress := createBlockchainCmd.String("address", "", "The address to send genesis block reward to")
sendFrom := sendCmd.String("from", "", "Source wallet address")
sendTo := sendCmd.String("to", "", "Destination wallet address")
sendAmount := sendCmd.Int("amount", 0, "Amount to send")
switch os.Args[1] {
case "getbalance":
err := getBalanceCmd.Parse(os.Args[2:])
if err != nil {
log.Panic(err)
}
case "createblockchain":
err := createBlockchainCmd.Parse(os.Args[2:])
if err != nil {
log.Panic(err)
}
case "createwallet":
err := createWalletCmd.Parse(os.Args[2:])
if err != nil {
log.Panic(err)
}
case "listaddresses":
err := listAddressesCmd.Parse(os.Args[2:])
if err != nil {
log.Panic(err)
}
case "printchain":
err := printChainCmd.Parse(os.Args[2:])
if err != nil {
log.Panic(err)
}
case "send":
err := sendCmd.Parse(os.Args[2:])
if err != nil {
log.Panic(err)
}
case "reindexutxo":
err := reindexUTXOCmd.Parse(os.Args[2:])
if err != nil {
log.Panic(err)
}
default:
cli.printUsage()
os.Exit(1)
}
if getBalanceCmd.Parsed() {
if *getBalanceAddress == "" {
getBalanceCmd.Usage()
os.Exit(1)
}
cli.getBalance(*getBalanceAddress)
}
if createBlockchainCmd.Parsed() {
if *createBlockchainAddress == "" {
createBlockchainCmd.Usage()
os.Exit(1)
}
cli.createBlockchain(*createBlockchainAddress)
}
if createWalletCmd.Parsed() {
cli.createWallet()
}
if listAddressesCmd.Parsed() {
cli.listAddresses()
}
if printChainCmd.Parsed() {
cli.printChain()
}
if reindexUTXOCmd.Parsed() {
cli.reindexUTXO()
}
if sendCmd.Parsed() {
if *sendFrom == "" || *sendTo == "" || *sendAmount <= 0 {
sendCmd.Usage()
os.Exit(1)
}
cli.send(*sendFrom, *sendTo, *sendAmount)
}
}