/
wallet.go
541 lines (457 loc) · 16.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package btc
import (
"bytes"
"context"
"encoding/base64"
"path/filepath"
"sync"
"time"
"decred.org/dcrwallet/v3/errors"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/gcs"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/chain"
_ "github.com/btcsuite/btcwallet/walletdb/bdb" // bdb init() registers a driver
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/btc"
"github.com/crypto-power/cryptopower/libwallet/utils"
"github.com/lightninglabs/neutrino"
"github.com/lightninglabs/neutrino/headerfs"
)
// Asset confirm that BTC implements that shared assets interface.
var _ sharedW.Asset = (*Asset)(nil)
// Asset is a wrapper around the btcwallet.Wallet struct.
// It implements the sharedW.Asset interface.
// It also implements the sharedW.AssetsManagerDB interface.
// This is done to allow the Asset to be used as a db interface
// for the AssetsManager.
type Asset struct {
*sharedW.Wallet
chainClient *chain.NeutrinoClient
chainParams *chaincfg.Params
TxAuthoredInfo *TxAuthor
cancelSync context.CancelFunc
syncCtx context.Context
// variables help manage node level tcp connections.
dailerCtx context.Context
dailerCancel context.CancelFunc
// This field has been added to cache the expensive call to GetTransactions.
// If the best block height hasn't changed there is no need to make another
// expensive GetTransactions call.
txs txCache
// This fields helps to prevent unnecessary API calls if a new block hasn't
// been introduced.
fees feeEstimateCache
// rescanStarting is set while reloading the wallet and dropping
// transactions from the wallet db.
rescanStarting uint32 // atomic
notificationListenersMu sync.RWMutex
syncData *SyncData
txAndBlockNotificationListeners map[string]*sharedW.TxAndBlockNotificationListener
blocksRescanProgressListener *sharedW.BlocksRescanProgressListener
}
const (
recoverWindow = 200 // If recoveryWindow is set to 0, there will be invalid block filter error.
defaultDBTimeout = time.Duration(100)
)
// neutrinoService is satisfied by *neutrino.ChainService.
type neutrinoService interface {
GetBlockHash(int64) (*chainhash.Hash, error)
BestBlock() (*headerfs.BlockStamp, error)
Peers() []*neutrino.ServerPeer
GetBlockHeight(hash *chainhash.Hash) (int32, error)
GetBlockHeader(*chainhash.Hash) (*wire.BlockHeader, error)
GetCFilter(blockHash chainhash.Hash, filterType wire.FilterType, options ...neutrino.QueryOption) (*gcs.Filter, error)
GetBlock(blockHash chainhash.Hash, options ...neutrino.QueryOption) (*btcutil.Block, error)
Stop() error
}
var _ neutrinoService = (*neutrino.ChainService)(nil)
// CreateNewWallet creates a new wallet for the BTC asset.
func CreateNewWallet(pass *sharedW.AuthInfo, params *sharedW.InitParams) (sharedW.Asset, error) {
chainParams, err := utils.BTCChainParams(params.NetType)
if err != nil {
return nil, err
}
ldr := initWalletLoader(chainParams, params.RootDir)
w, err := sharedW.CreateNewWallet(pass, ldr, params, utils.BTCWalletAsset)
if err != nil {
return nil, err
}
btcWallet := &Asset{
Wallet: w,
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
}
if err := btcWallet.prepareChain(); err != nil {
return nil, err
}
btcWallet.SetNetworkCancelCallback(btcWallet.SafelyCancelSync)
return btcWallet, nil
}
func initWalletLoader(chainParams *chaincfg.Params, dbDirPath string) loader.AssetLoader {
dirName := ""
// testnet datadir takes a special structure differentiating "testnet4" and "testnet3"
// data directory.
if utils.ToNetworkType(chainParams.Net.String()) == utils.Testnet {
dirName = utils.NetDir(utils.BTCWalletAsset, utils.Testnet)
}
conf := &btc.LoaderConf{
ChainParams: chainParams,
DBDirPath: filepath.Join(dbDirPath, dirName),
DefaultDBTimeout: defaultDBTimeout,
RecoveryWin: recoverWindow,
Keyscope: GetScope(),
}
return btc.NewLoader(conf)
}
// CreateWatchOnlyWallet accepts the wallet name, extended public key and the
// init parameters to create a watch only wallet for the BTC asset.
// It validates the network type passed by fetching the chain parameters
// associated with it for the BTC asset. It then generates the BTC 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.BTCChainParams(params.NetType)
if err != nil {
return nil, err
}
ldr := initWalletLoader(chainParams, params.RootDir)
w, err := sharedW.CreateWatchOnlyWallet(walletName, extendedPublicKey,
ldr, params, utils.BTCWalletAsset)
if err != nil {
return nil, err
}
btcWallet := &Asset{
Wallet: w,
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
}
if err := btcWallet.prepareChain(); err != nil {
return nil, err
}
btcWallet.SetNetworkCancelCallback(btcWallet.SafelyCancelSync)
return btcWallet, 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 BTC asset. It then generates the BTC
// 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.BTCChainParams(params.NetType)
if err != nil {
return nil, err
}
ldr := initWalletLoader(chainParams, params.RootDir)
w, err := sharedW.RestoreWallet(seedMnemonic, pass, ldr, params, utils.BTCWalletAsset)
if err != nil {
return nil, err
}
btcWallet := &Asset{
Wallet: w,
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
}
if err := btcWallet.prepareChain(); err != nil {
return nil, err
}
btcWallet.SetNetworkCancelCallback(btcWallet.SafelyCancelSync)
return btcWallet, 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 BTC asset. It then generates the BTC loader interface
// that is passed to be used upstream while loading the existing the wallet in the
// shared wallet implemenation.
// 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.BTCChainParams(params.NetType)
if err != nil {
return nil, err
}
// If a wallet doesn't contain discovered accounts, its previous recovery wasn't
// successful and therefore it should try the recovery again till it successfully
// completes.
ldr := initWalletLoader(chainParams, params.RootDir)
btcWallet := &Asset{
Wallet: w,
chainParams: chainParams,
syncData: &SyncData{
syncProgressListeners: make(map[string]*sharedW.SyncProgressListener),
},
txAndBlockNotificationListeners: make(map[string]*sharedW.TxAndBlockNotificationListener),
}
err = btcWallet.Prepare(ldr, params)
if err != nil {
return nil, err
}
if err := btcWallet.prepareChain(); err != nil {
return nil, err
}
btcWallet.SetNetworkCancelCallback(btcWallet.SafelyCancelSync)
return btcWallet, nil
}
// SafelyCancelSync shuts down all the upstream processes. If not explicitly
// deleting a wallet use asset.CancelSync() instead.
func (asset *Asset) SafelyCancelSync() {
if asset.IsConnectedToNetwork() {
// Chain is either syncing or is synced.
asset.CancelSync()
}
loadWallet := asset.Internal().BTC
if asset.WalletOpened() && loadWallet.Database() != nil {
// Close the upstream loader database connection.
if err := loadWallet.Database().Close(); err != nil {
log.Errorf("closing upstream db failed: %v", err)
}
}
asset.syncData.wg.Wait()
// Stop the goroutines left active to manage the wallet functionalities that
// don't require activation of sync i.e. wallet rename, password update etc.
if asset.WalletOpened() {
if loadWallet.ShuttingDown() {
return
}
loadWallet.Stop()
loadWallet.WaitForShutdown()
}
}
func (asset *Asset) NeutrinoClient() *chain.NeutrinoClient {
return asset.chainClient
}
// IsSynced returns true if the wallet is synced.
func (asset *Asset) IsSynced() bool {
asset.syncData.mu.RLock()
defer asset.syncData.mu.RUnlock()
return asset.syncData.synced
}
// IsWaiting returns true if the wallet is waiting for headers.
func (asset *Asset) IsWaiting() bool {
log.Warn(utils.ErrBTCMethodNotImplemented("IsWaiting"))
return false
}
// IsSyncing returns true if the wallet is syncing.
func (asset *Asset) IsSyncing() bool {
asset.syncData.mu.RLock()
defer asset.syncData.mu.RUnlock()
return asset.syncData.syncing
}
// IsSyncShuttingDown returns true if the wallet is shutting down.
func (asset *Asset) IsSyncShuttingDown() bool {
asset.syncData.mu.RLock()
defer asset.syncData.mu.RUnlock()
return asset.syncData.isSyncShuttingDown
}
// ConnectedPeers returns the number of connected peers.
func (asset *Asset) ConnectedPeers() int32 {
// Calling CS.ConnectedCount() before the first sync is
// Performed will freeze the application, because the function never return.
// Return 0 when not connected to bitcoin network as work around.
if !asset.IsConnectedToNetwork() {
return -1
}
return asset.chainClient.CS.ConnectedCount()
}
// IsConnectedToNetwork returns true if the wallet is connected to the network.
func (asset *Asset) IsConnectedToNetwork() bool {
return asset.IsConnectedToBitcoinNetwork()
}
// GetBestBlock returns the best block.
func (asset *Asset) GetBestBlock() *sharedW.BlockInfo {
block, err := asset.chainClient.CS.BestBlock()
if err != nil {
log.Error("GetBestBlock hash for BTC failed, Err: ", err)
return sharedW.InvalidBlock
}
return &sharedW.BlockInfo{
Height: block.Height,
Timestamp: block.Timestamp.Unix(),
}
}
// GetBestBlockHeight returns the best block height.
func (asset *Asset) GetBestBlockHeight() int32 {
return asset.GetBestBlock().Height
}
// GetBestBlockTimeStamp returns the best block timestamp.
func (asset *Asset) GetBestBlockTimeStamp() int64 {
return asset.GetBestBlock().Timestamp
}
// GetBlockHeight returns the block height for the given block hash.
func (asset *Asset) GetBlockHeight(hash chainhash.Hash) (int32, error) {
height, err := asset.chainClient.GetBlockHeight(&hash)
if err != nil {
log.Warn("GetBlockHeight for BTC failed, Err: %v", err)
return -1, err
}
return height, nil
}
// GetBlockHash returns the block hash for the given block height.
func (asset *Asset) GetBlockHash(height int64) (*chainhash.Hash, error) {
blockhash, err := asset.chainClient.GetBlockHash(height)
if err != nil {
log.Warn("GetBlockHash for BTC failed, Err: %v", err)
return nil, err
}
return blockhash, nil
}
// SignMessage signs a message with the private key associated with an address.
func (asset *Asset) SignMessage(passphrase, address, message string) ([]byte, error) {
err := asset.UnlockWallet(passphrase)
if err != nil {
return nil, err
}
defer asset.LockWallet()
addr, err := decodeAddress(address, asset.chainParams)
if err != nil {
return nil, err
}
privKey, err := asset.Internal().BTC.PrivKeyForAddress(addr)
if err != nil {
return nil, err
}
var buf bytes.Buffer
err = wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n")
if err != nil {
return nil, err
}
err = wire.WriteVarString(&buf, 0, message)
if err != nil {
return nil, err
}
messageHash := chainhash.DoubleHashB(buf.Bytes())
sigbytes, err := ecdsa.SignCompact(privKey, messageHash, true)
if err != nil {
return nil, err
}
return sigbytes, nil
}
// VerifyMessage verifies a signed message.
func (asset *Asset) VerifyMessage(address, message, signatureBase64 string) (bool, error) {
addr, err := decodeAddress(address, asset.chainParams)
if err != nil {
return false, err
}
// decode base64 signature
sig, err := base64.StdEncoding.DecodeString(signatureBase64)
if err != nil {
return false, err
}
// Validate the signature - this just shows that it was valid at all.
// we will compare it with the key next.
var buf bytes.Buffer
err = wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n")
if err != nil {
return false, nil
}
err = wire.WriteVarString(&buf, 0, message)
if err != nil {
return false, nil
}
expectedMessageHash := chainhash.DoubleHashB(buf.Bytes())
pk, wasCompressed, err := ecdsa.RecoverCompact(sig, expectedMessageHash)
if err != nil {
return false, err
}
var serializedPubKey []byte
if wasCompressed {
serializedPubKey = pk.SerializeCompressed()
} else {
serializedPubKey = pk.SerializeUncompressed()
}
// Verify that the signed-by address matches the given address
switch checkAddr := addr.(type) {
case *btcutil.AddressPubKeyHash:
return bytes.Equal(btcutil.Hash160(serializedPubKey), checkAddr.Hash160()[:]), nil
case *btcutil.AddressPubKey:
return string(serializedPubKey) == checkAddr.String(), nil
case *btcutil.AddressWitnessPubKeyHash:
byteEq := bytes.Compare(btcutil.Hash160(serializedPubKey), checkAddr.Hash160()[:])
return byteEq == 0, nil
default:
return false, errors.New("address type not supported")
}
}
// RemovePeers removes all peers from the wallet.
func (asset *Asset) RemovePeers() {
asset.SaveUserConfigValue(sharedW.SpvPersistentPeerAddressesConfigKey, "")
go func() {
err := asset.reloadChainService()
if err != nil {
log.Error(err)
}
}()
}
// SetSpecificPeer sets a specific peer or list of peer to connect to.
func (asset *Asset) SetSpecificPeer(addresses string) {
asset.SaveUserConfigValue(sharedW.SpvPersistentPeerAddressesConfigKey, addresses)
go func() {
err := asset.reloadChainService()
if err != nil {
log.Error(err)
}
}()
}
// GetExtendedPubKey returns the extended public key of the given account,
// to do that it calls btcwallet's AccountProperties method, using KeyScopeBIP0084
// and the account number. On failure it returns error.
func (asset *Asset) GetExtendedPubKey(account int32) (string, error) {
loadedAsset := asset.Internal().BTC
if loadedAsset == nil {
return "", utils.ErrBTCNotInitialized
}
extendedPublicKey, err := loadedAsset.AccountProperties(GetScope(), uint32(account))
if err != nil {
return "", err
}
return extendedPublicKey.AccountPubKey.String(), nil
}
// AccountXPubMatches checks if the xpub of the provided account matches the
// provided xpub.
func (asset *Asset) AccountXPubMatches(account uint32, xPub string) (bool, error) {
acctXPubKey, err := asset.Internal().BTC.AccountProperties(GetScope(), account)
if err != nil {
return false, err
}
return acctXPubKey.AccountPubKey.String() == xPub, nil
}
// GetWalletBalance returns the total balance across all accounts.
func (asset *Asset) GetWalletBalance() (*sharedW.Balance, error) {
if !asset.WalletOpened() {
return nil, utils.ErrBTCNotInitialized
}
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),
ImmatureReward: Amount(totalImmatureReward),
Locked: Amount(totalLocked),
}, nil
}