-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwallets.go
More file actions
95 lines (74 loc) · 1.82 KB
/
wallets.go
File metadata and controls
95 lines (74 loc) · 1.82 KB
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
package main
import (
"bytes"
"crypto/elliptic"
"encoding/gob"
"fmt"
"io/ioutil"
"log"
"os"
)
const walletFile = "wallet.dat"
// WalletMap stores a collection of wallets
type Wallets struct {
WalletMap map[string]*Wallet
}
// NewWallets creates WalletMap and fills it from a file if it exists
func NewWallets() (*Wallets, error) {
wallets := Wallets{}
wallets.WalletMap = make(map[string]*Wallet)
err := wallets.LoadFromFile()
return &wallets, err
}
// CreateWallet adds a Wallet to WalletMap
func (ws *Wallets) CreateWallet() string {
wallet := NewWallet()
address := fmt.Sprintf("%s", wallet.GetAddress())
ws.WalletMap[address] = wallet
return address
}
// GetAddresses returns an array of addresses stored in the wallet file
func (ws *Wallets) GetAddresses() []string {
var addresses []string
for address := range ws.WalletMap {
addresses = append(addresses, address)
}
return addresses
}
// GetWallet returns a Wallet by its Address
func (ws Wallets) GetWallet(address string) Wallet {
return *ws.WalletMap[address]
}
// LoadPeersFromFile loads wallets from the file
func (ws *Wallets) LoadFromFile() error {
if _, err := os.Stat(walletFile); os.IsNotExist(err) {
return err
}
fileContent, err := ioutil.ReadFile(walletFile)
if err != nil {
log.Panic(err)
}
var wallets Wallets
gob.Register(elliptic.P256())
decoder := gob.NewDecoder(bytes.NewReader(fileContent))
err = decoder.Decode(&wallets)
if err != nil {
log.Panic(err)
}
ws.WalletMap = wallets.WalletMap
return nil
}
// SaveToFile saves wallets to a file
func (ws Wallets) SaveToFile() {
var content bytes.Buffer
gob.Register(elliptic.P256())
encoder := gob.NewEncoder(&content)
err := encoder.Encode(ws)
if err != nil {
log.Panic(err)
}
err = ioutil.WriteFile(walletFile, content.Bytes(), 0644)
if err != nil {
log.Panic(err)
}
}