Implement 'getbalance' command

This commit is contained in:
Ivan Kuznetsov 2017-09-03 11:02:46 +07:00
parent f83ccd7b4c
commit 87eb17bbe5
1 changed files with 34 additions and 2 deletions

36
cli.go
View File

@ -13,10 +13,27 @@ type CLI struct {
bc *Blockchain
}
func (cli *CLI) getBalance(address string) {
balance := 0
utxs := cli.bc.FindUnspentTransactions(address)
for _, tx := range utxs {
for _, out := range tx.Vout {
if out.Unlock(address) {
balance += out.Value
}
}
}
fmt.Printf("Balance of '%s': %d\n", address, balance)
}
func (cli *CLI) printUsage() {
fmt.Println("Usage:")
fmt.Println(" printchain - print all the blocks of the blockchain")
fmt.Println(" send -from FROM -to TO -amount AMOUNT - send AMOUNT of coins from FROM address to TO")
fmt.Println(" getbalance -address ADDRESS - Get balance of ADDRESS")
fmt.Println(" printchain - Print all the blocks of the blockchain")
fmt.Println(" send -from FROM -to TO -amount AMOUNT - Send AMOUNT of coins from FROM address to TO")
}
func (cli *CLI) validateArgs() {
@ -54,14 +71,21 @@ func (cli *CLI) send(from, to string, amount int) {
func (cli *CLI) Run() {
cli.validateArgs()
getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError)
sendCmd := flag.NewFlagSet("send", flag.ExitOnError)
printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError)
getBalanceAddress := getBalanceCmd.String("address", "", "The address to get balance for")
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 "printchain":
err := printChainCmd.Parse(os.Args[2:])
if err != nil {
@ -77,6 +101,14 @@ func (cli *CLI) Run() {
os.Exit(1)
}
if getBalanceCmd.Parsed() {
if *getBalanceAddress == "" {
getBalanceCmd.Usage()
os.Exit(1)
}
cli.getBalance(*getBalanceAddress)
}
if printChainCmd.Parsed() {
cli.printChain()
}