-
Notifications
You must be signed in to change notification settings - Fork 23
/
wallet.go
336 lines (284 loc) · 11.5 KB
/
wallet.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package dcr
import (
"context"
"errors"
"path/filepath"
"sync"
dcrW "decred.org/dcrwallet/v3/wallet"
"decred.org/dcrwallet/v3/wallet/txrules"
sharedW "github.com/crypto-power/cryptopower/libwallet/assets/wallet"
"github.com/crypto-power/cryptopower/libwallet/internal/loader"
"github.com/crypto-power/cryptopower/libwallet/internal/loader/dcr"
"github.com/crypto-power/cryptopower/libwallet/internal/vsp"
"github.com/crypto-power/cryptopower/libwallet/utils"
"github.com/decred/dcrd/chaincfg/v3"
)
type Asset struct {
*sharedW.Wallet
synced bool
syncing bool
waitingForHeaders bool
chainParams *chaincfg.Params
cancelAccountMixer context.CancelFunc `json:"-"`
cancelAutoTicketBuyer context.CancelFunc `json:"-"`
cancelAutoTicketBuyerMu sync.RWMutex
TxAuthoredInfo *TxAuthor
vspClientsMu sync.Mutex
vspClients map[string]*vsp.Client
vspMu sync.RWMutex
vsps []*VSP
notificationListenersMu sync.RWMutex
syncData *SyncData
accountMixerNotificationListeners map[string]*AccountMixerNotificationListener
txAndBlockNotificationListeners map[string]*sharedW.TxAndBlockNotificationListener
blocksRescanProgressListener *sharedW.BlocksRescanProgressListener
// dbMutex should be held when db transactions would circle back around
// and hold the mu lock to prevent a freeze.
dbMutex *sync.Mutex
}
// Verify that DCR implements the shared assets interface.
var _ sharedW.Asset = (*Asset)(nil)
// initWalletLoader setups the loader.
func initWalletLoader(chainParams *chaincfg.Params, rootdir, walletDbDriver string, dbMutex *sync.Mutex) loader.AssetLoader {
// TODO: Allow users provide values to override these defaults.
cfg := &sharedW.WConfig{
GapLimit: 20,
AllowHighFees: false,
RelayFee: txrules.DefaultRelayFeePerKb,
AccountGapLimit: dcrW.DefaultAccountGapLimit,
DisableCoinTypeUpgrades: false,
ManualTickets: false,
MixSplitLimit: 10,
}
stakeOptions := &dcr.StakeOptions{
VotingEnabled: false,
AddressReuse: false,
VotingAddress: nil,
}
dirName := ""
// testnet datadir takes a special structure to differentiate "testnet4" and "testnet3"
// data directory.
if utils.ToNetworkType(chainParams.Net.String()) == utils.Testnet {
dirName = utils.NetDir(utils.DCRWalletAsset, utils.Testnet)
}
loaderCfg := &dcr.LoaderConf{
ChainParams: chainParams,
DBDirPath: filepath.Join(rootdir, dirName),
StakeOptions: stakeOptions,
GapLimit: cfg.GapLimit,
RelayFee: cfg.RelayFee,
AllowHighFees: cfg.AllowHighFees,
DisableCoinTypeUpgrades: cfg.DisableCoinTypeUpgrades,
ManualTickets: cfg.ManualTickets,
AccountGapLimit: cfg.AccountGapLimit,
MixSplitLimit: cfg.MixSplitLimit,
DBMutex: dbMutex,
}
walletLoader := dcr.NewLoader(loaderCfg)
if walletDbDriver != "" {
walletLoader.SetDatabaseDriver(walletDbDriver)
}
return walletLoader
}
// CreateNewWallet accepts the wallet pass information and the init parameters.
// It validates the network type passed by fetching the chain parameters
// associated with it for the DCR asset. It then generates the DCR loader interface
// that is passed to be used upstream while creating a new wallet in the
// shared wallet implementation.
// Immediately a new wallet is created, the function to safely cancel network sync
// is set. There after returning the new wallet's interface.
func CreateNewWallet(pass *sharedW.AuthInfo, params *sharedW.InitParams) (sharedW.Asset, error) {
chainParams, err := utils.DCRChainParams(params.NetType)
if err != nil {
return nil, err
}
var dbMutex sync.Mutex
ldr := initWalletLoader(chainParams, params.RootDir, params.DbDriver, &dbMutex)
w, err := sharedW.CreateNewWallet(pass, ldr, params, utils.DCRWalletAsset)
if err != nil {
return nil, err
}
dcrWallet := &Asset{
Wallet: w,
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
accountMixerNotificationListeners: make(map[string]*AccountMixerNotificationListener),
vspClients: make(map[string]*vsp.Client),
dbMutex: &dbMutex,
}
dcrWallet.SetNetworkCancelCallback(dcrWallet.SafelyCancelSync)
return dcrWallet, nil
}
// CreateWatchOnlyWallet accepts the wallet name, extended public key and the
// init parameters to create a watch only wallet for the DCR asset.
// It validates the network type passed by fetching the chain parameters
// associated with it for the DCR asset. It then generates the DCR loader interface
// that is passed to be used upstream while creating the watch only wallet in the
// shared wallet implementation.
// Immediately a watch only wallet is created, the function to safely cancel network sync
// is set. There after returning the watch only wallet's interface.
func CreateWatchOnlyWallet(walletName, extendedPublicKey string, params *sharedW.InitParams) (sharedW.Asset, error) {
chainParams, err := utils.DCRChainParams(params.NetType)
if err != nil {
return nil, err
}
var dbMutex sync.Mutex
ldr := initWalletLoader(chainParams, params.RootDir, params.DbDriver, &dbMutex)
w, err := sharedW.CreateWatchOnlyWallet(walletName, extendedPublicKey,
ldr, params, utils.DCRWalletAsset)
if err != nil {
return nil, err
}
dcrWallet := &Asset{
Wallet: w,
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
accountMixerNotificationListeners: make(map[string]*AccountMixerNotificationListener),
dbMutex: &dbMutex,
}
dcrWallet.SetNetworkCancelCallback(dcrWallet.SafelyCancelSync)
return dcrWallet, nil
}
// RestoreWallet accepts the seed, wallet pass information and the init parameters.
// It validates the network type passed by fetching the chain parameters
// associated with it for the DCR asset. It then generates the DCR loader interface
// that is passed to be used upstream while restoring the wallet in the
// shared wallet implementation.
// Immediately wallet restore is complete, the function to safely cancel network sync
// is set. There after returning the restored wallet's interface.
func RestoreWallet(seedMnemonic string, pass *sharedW.AuthInfo, params *sharedW.InitParams) (sharedW.Asset, error) {
chainParams, err := utils.DCRChainParams(params.NetType)
if err != nil {
return nil, err
}
var dbMutex sync.Mutex
ldr := initWalletLoader(chainParams, params.RootDir, params.DbDriver, &dbMutex)
w, err := sharedW.RestoreWallet(seedMnemonic, pass, ldr, params, utils.DCRWalletAsset)
if err != nil {
return nil, err
}
dcrWallet := &Asset{
Wallet: w,
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
vspClients: make(map[string]*vsp.Client),
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
accountMixerNotificationListeners: make(map[string]*AccountMixerNotificationListener),
dbMutex: &dbMutex,
}
dcrWallet.SetNetworkCancelCallback(dcrWallet.SafelyCancelSync)
return dcrWallet, nil
}
// LoadExisting accepts the stored shared wallet information and the init parameters.
// It validates the network type passed by fetching the chain parameters
// associated with it for the DCR asset. It then generates the DCR loader interface
// that is passed to be used upstream while loading the existing the wallet in the
// shared wallet implementation.
// Immediately loading the existing wallet is complete, the function to safely
// cancel network sync is set. There after returning the loaded wallet's interface.
func LoadExisting(w *sharedW.Wallet, params *sharedW.InitParams) (sharedW.Asset, error) {
chainParams, err := utils.DCRChainParams(params.NetType)
if err != nil {
return nil, err
}
var dbMutex sync.Mutex
ldr := initWalletLoader(chainParams, params.RootDir, params.DbDriver, &dbMutex)
dcrWallet := &Asset{
Wallet: w,
vspClients: make(map[string]*vsp.Client),
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
accountMixerNotificationListeners: make(map[string]*AccountMixerNotificationListener),
dbMutex: &dbMutex,
}
// w.EncryptedSeed was previously deleted after verification. Existing
// wallets created before the change to allow viewing wallet seed in-app
// should still behave normal but they can no longer view their seed.
if len(w.EncryptedSeed) == 0 && !w.IsBackedUp {
w.IsBackedUp = true
if err := params.DB.Save(w); err != nil {
log.Errorf("DB.Save error: %v", err)
return nil, errors.New("failed to update wallet back up state")
}
}
err = dcrWallet.Prepare(ldr, params)
if err != nil {
return nil, err
}
dcrWallet.SetNetworkCancelCallback(dcrWallet.SafelyCancelSync)
return dcrWallet, nil
}
// AccountXPubMatches checks if the xpub of the provided account matches the
// provided legacy or SLIP0044 xpub. While both the legacy and SLIP0044 xpubs
// will be checked for watch-only wallets, other wallets will only check the
// xpub that matches the coin type key used by the asset.
func (asset *Asset) AccountXPubMatches(account uint32, legacyXPub, slip044XPub string) (bool, error) {
if !asset.WalletOpened() {
return false, utils.ErrDCRNotInitialized
}
ctx, _ := asset.ShutdownContextWithCancel()
acctXPubKey, err := asset.Internal().DCR.AccountXpub(ctx, account)
if err != nil {
return false, err
}
acctXPub := acctXPubKey.String()
if asset.IsWatchingOnlyWallet() {
// Coin type info isn't saved for watch-only wallets, so check
// against both legacy and SLIP0044 coin types.
return acctXPub == legacyXPub || acctXPub == slip044XPub, nil
}
cointype, err := asset.Internal().DCR.CoinType(ctx)
if err != nil {
return false, err
}
if cointype == asset.chainParams.LegacyCoinType {
return acctXPub == legacyXPub, nil
}
return acctXPub == slip044XPub, nil
}
func (asset *Asset) Synced() bool {
return asset.synced
}
// SafelyCancelSync is used to controllably disable network activity.
func (asset *Asset) SafelyCancelSync() {
if asset.IsConnectedToDecredNetwork() {
asset.CancelSync()
}
}
func (asset *Asset) IsConnectedToNetwork() bool {
return asset.IsConnectedToDecredNetwork()
}
// GetWalletBalance returns the total balance across all accounts.
func (asset *Asset) GetWalletBalance() (*sharedW.Balance, error) {
if !asset.WalletOpened() {
return nil, utils.ErrDCRNotInitialized
}
accountsResult, err := asset.GetAccountsRaw()
if err != nil {
return nil, err
}
var totalBalance, totalSpendable, totalImmatureReward, totalLocked int64
for _, acc := range accountsResult.Accounts {
totalBalance += acc.Balance.Total.ToInt()
totalSpendable += acc.Balance.Spendable.ToInt()
totalImmatureReward += acc.Balance.ImmatureReward.ToInt()
totalLocked += acc.Balance.Locked.ToInt()
}
return &sharedW.Balance{
Total: Amount(totalBalance),
Spendable: Amount(totalSpendable - totalLocked),
ImmatureReward: Amount(totalImmatureReward),
Locked: Amount(totalLocked),
}, nil
}