-
Notifications
You must be signed in to change notification settings - Fork 0
/
balance.go
57 lines (45 loc) · 1.21 KB
/
balance.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
package cmd
import (
"fmt"
"log"
"os"
"github.com/spf13/cobra"
"github.com/erxonxi/coin/blockchain"
"github.com/erxonxi/coin/wallet"
)
// balanceCmd represents the balance command
var balanceCmd = &cobra.Command{
Use: "balance",
Short: "Command to get balance.",
Long: `Command to get balance.
For example:
coin balance --address "15AfJY1BtvMsD5Zzd7mtBLyaxQavTESxaa"
`,
Run: func(cmd *cobra.Command, args []string) {
getBalance()
},
}
func init() {
rootCmd.AddCommand(balanceCmd)
balanceCmd.Flags().StringVarP((&address), "address", "a", "15AfJY1BtvMsD5Zzd7mtBLyaxQavTESxaa", "Your address of blockchain")
}
func getBalance() {
nodeID := os.Getenv("NODE_ID")
if nodeID == "" {
log.Panic("Please provide a NODE_ID")
}
if !wallet.ValidateAddress(address) {
log.Panic("Address is not Valid")
}
chain := blockchain.ContinueBlockChain(nodeID)
UTXOSet := blockchain.UTXOSet{Blockchain: chain}
defer chain.Database.Close()
balance := 0
pubKeyHash := wallet.Base58Decode([]byte(address))
pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4]
UTXOs := UTXOSet.FindUnspentTransactions(pubKeyHash)
for _, out := range UTXOs {
balance += out.Value
}
fmt.Printf("Balance of %s: %d\n", address, balance)
}