-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
btcwallet.go
1931 lines (1648 loc) · 60.5 KB
/
btcwallet.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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package btcwallet
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"math"
"sync"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/waddrmgr"
base "github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcwallet/wallet/txrules"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/blockcache"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
)
const (
defaultAccount = uint32(waddrmgr.DefaultAccountNum)
importedAccount = uint32(waddrmgr.ImportedAddrAccount)
// dryRunImportAccountNumAddrs represents the number of addresses we'll
// derive for an imported account's external and internal branch when a
// dry run is attempted.
dryRunImportAccountNumAddrs = 5
// UnconfirmedHeight is the special case end height that is used to
// obtain unconfirmed transactions from ListTransactionDetails.
UnconfirmedHeight int32 = -1
// walletMetaBucket is used to store wallet metadata.
walletMetaBucket = "lnwallet"
// walletReadyKey is used to indicate that the wallet has been
// initialized.
walletReadyKey = "ready"
)
var (
// waddrmgrNamespaceKey is the namespace key that the waddrmgr state is
// stored within the top-level walletdb buckets of btcwallet.
waddrmgrNamespaceKey = []byte("waddrmgr")
// wtxmgrNamespaceKey is the namespace key that the wtxmgr state is
// stored within the top-level waleltdb buckets of btcwallet.
wtxmgrNamespaceKey = []byte("wtxmgr")
// lightningAddrSchema is the scope addr schema for all keys that we
// derive. We'll treat them all as p2wkh addresses, as atm we must
// specify a particular type.
lightningAddrSchema = waddrmgr.ScopeAddrSchema{
ExternalAddrType: waddrmgr.WitnessPubKey,
InternalAddrType: waddrmgr.WitnessPubKey,
}
// LndDefaultKeyScopes is the list of default key scopes that lnd adds
// to its wallet.
LndDefaultKeyScopes = []waddrmgr.KeyScope{
waddrmgr.KeyScopeBIP0049Plus,
waddrmgr.KeyScopeBIP0084,
waddrmgr.KeyScopeBIP0086,
}
// errNoImportedAddrGen is an error returned when a new address is
// requested for the default imported account within the wallet.
errNoImportedAddrGen = errors.New("addresses cannot be generated for " +
"the default imported account")
)
// BtcWallet is an implementation of the lnwallet.WalletController interface
// backed by an active instance of btcwallet. At the time of the writing of
// this documentation, this implementation requires a full btcd node to
// operate.
type BtcWallet struct {
// wallet is an active instance of btcwallet.
wallet *base.Wallet
chain chain.Interface
db walletdb.DB
cfg *Config
netParams *chaincfg.Params
chainKeyScope waddrmgr.KeyScope
blockCache *blockcache.BlockCache
*input.MusigSessionManager
}
// A compile time check to ensure that BtcWallet implements the
// WalletController and BlockChainIO interfaces.
var _ lnwallet.WalletController = (*BtcWallet)(nil)
var _ lnwallet.BlockChainIO = (*BtcWallet)(nil)
// New returns a new fully initialized instance of BtcWallet given a valid
// configuration struct.
func New(cfg Config, blockCache *blockcache.BlockCache) (*BtcWallet, error) {
// Create the key scope for the coin type being managed by this wallet.
chainKeyScope := waddrmgr.KeyScope{
Purpose: keychain.BIP0043Purpose,
Coin: cfg.CoinType,
}
// Maybe the wallet has already been opened and unlocked by the
// WalletUnlocker. So if we get a non-nil value from the config,
// we assume everything is in order.
var wallet = cfg.Wallet
if wallet == nil {
// No ready wallet was passed, so try to open an existing one.
var pubPass []byte
if cfg.PublicPass == nil {
pubPass = defaultPubPassphrase
} else {
pubPass = cfg.PublicPass
}
loader, err := NewWalletLoader(
cfg.NetParams, cfg.RecoveryWindow, cfg.LoaderOptions...,
)
if err != nil {
return nil, err
}
walletExists, err := loader.WalletExists()
if err != nil {
return nil, err
}
if !walletExists {
// Wallet has never been created, perform initial
// set up.
wallet, err = loader.CreateNewWallet(
pubPass, cfg.PrivatePass, cfg.HdSeed,
cfg.Birthday,
)
if err != nil {
return nil, err
}
} else {
// Wallet has been created and been initialized at
// this point, open it along with all the required DB
// namespaces, and the DB itself.
wallet, err = loader.OpenExistingWallet(pubPass, false)
if err != nil {
return nil, err
}
}
}
finalWallet := &BtcWallet{
cfg: &cfg,
wallet: wallet,
db: wallet.Database(),
chain: cfg.ChainSource,
netParams: cfg.NetParams,
chainKeyScope: chainKeyScope,
blockCache: blockCache,
}
finalWallet.MusigSessionManager = input.NewMusigSessionManager(
finalWallet.fetchPrivKey,
)
return finalWallet, nil
}
// loaderCfg holds optional wallet loader configuration.
type loaderCfg struct {
dbDirPath string
noFreelistSync bool
dbTimeout time.Duration
useLocalDB bool
externalDB kvdb.Backend
}
// LoaderOption is a functional option to update the optional loader config.
type LoaderOption func(*loaderCfg)
// LoaderWithLocalWalletDB configures the wallet loader to use the local db.
func LoaderWithLocalWalletDB(dbDirPath string, noFreelistSync bool,
dbTimeout time.Duration) LoaderOption {
return func(cfg *loaderCfg) {
cfg.dbDirPath = dbDirPath
cfg.noFreelistSync = noFreelistSync
cfg.dbTimeout = dbTimeout
cfg.useLocalDB = true
}
}
// LoaderWithExternalWalletDB configures the wallet loadr to use an external db.
func LoaderWithExternalWalletDB(db kvdb.Backend) LoaderOption {
return func(cfg *loaderCfg) {
cfg.externalDB = db
}
}
// NewWalletLoader constructs a wallet loader.
func NewWalletLoader(chainParams *chaincfg.Params, recoveryWindow uint32,
opts ...LoaderOption) (*base.Loader, error) {
cfg := &loaderCfg{}
// Apply all functional options.
for _, o := range opts {
o(cfg)
}
if cfg.externalDB != nil && cfg.useLocalDB {
return nil, fmt.Errorf("wallet can either be in the local or " +
"an external db")
}
if cfg.externalDB != nil {
loader, err := base.NewLoaderWithDB(
chainParams, recoveryWindow, cfg.externalDB,
func() (bool, error) {
return externalWalletExists(cfg.externalDB)
},
)
if err != nil {
return nil, err
}
// Decorate wallet db with out own key such that we
// can always check whether the wallet exists or not.
loader.OnWalletCreated(onWalletCreated)
return loader, nil
}
return base.NewLoader(
chainParams, cfg.dbDirPath, cfg.noFreelistSync,
cfg.dbTimeout, recoveryWindow,
), nil
}
// externalWalletExists is a helper function that we use to template btcwallet's
// Loader in order to be able check if the wallet database has been initialized
// in an external DB.
func externalWalletExists(db kvdb.Backend) (bool, error) {
exists := false
err := kvdb.View(db, func(tx kvdb.RTx) error {
metaBucket := tx.ReadBucket([]byte(walletMetaBucket))
if metaBucket != nil {
walletReady := metaBucket.Get([]byte(walletReadyKey))
exists = string(walletReady) == walletReadyKey
}
return nil
}, func() {})
return exists, err
}
// onWalletCreated is executed when btcwallet creates the wallet the first time.
func onWalletCreated(tx kvdb.RwTx) error {
metaBucket, err := tx.CreateTopLevelBucket([]byte(walletMetaBucket))
if err != nil {
return err
}
return metaBucket.Put([]byte(walletReadyKey), []byte(walletReadyKey))
}
// BackEnd returns the underlying ChainService's name as a string.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) BackEnd() string {
if b.chain != nil {
return b.chain.BackEnd()
}
return ""
}
// InternalWallet returns a pointer to the internal base wallet which is the
// core of btcwallet.
func (b *BtcWallet) InternalWallet() *base.Wallet {
return b.wallet
}
// Start initializes the underlying rpc connection, the wallet itself, and
// begins syncing to the current available blockchain state.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) Start() error {
// Is the wallet (according to its database) currently watch-only
// already? If it is, we won't need to convert it later.
walletIsWatchOnly := b.wallet.Manager.WatchOnly()
// If the wallet is watch-only, but we don't expect it to be, then we
// are in an unexpected state and cannot continue.
if walletIsWatchOnly && !b.cfg.WatchOnly {
return fmt.Errorf("wallet is watch-only but we expect it " +
"not to be; check if remote signing was disabled by " +
"accident")
}
// We'll start by unlocking the wallet and ensuring that the KeyScope:
// (1017, 1) exists within the internal waddrmgr. We'll need this in
// order to properly generate the keys required for signing various
// contracts. If this is a watch-only wallet, we don't have any private
// keys and therefore unlocking is not necessary.
if !walletIsWatchOnly {
if err := b.wallet.Unlock(b.cfg.PrivatePass, nil); err != nil {
return err
}
// If the wallet isn't about to be converted, we need to inform
// the user that this wallet still contains all private key
// material and that they need to migrate the existing wallet.
if b.cfg.WatchOnly && !b.cfg.MigrateWatchOnly {
log.Warnf("Wallet is expected to be in watch-only " +
"mode but hasn't been migrated to watch-only " +
"yet, it still contains private keys; " +
"consider turning on the watch-only wallet " +
"migration in remote signing mode")
}
}
// Because we might add new "default" key scopes over time, they are
// created correctly for new wallets. Existing wallets don't
// automatically add them, we need to do that manually now.
for _, scope := range LndDefaultKeyScopes {
_, err := b.wallet.Manager.FetchScopedKeyManager(scope)
if waddrmgr.IsError(err, waddrmgr.ErrScopeNotFound) {
// The default scope wasn't found, that probably means
// it was added recently and older wallets don't know it
// yet. Let's add it now.
addrSchema := waddrmgr.ScopeAddrMap[scope]
err := walletdb.Update(
b.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(
waddrmgrNamespaceKey,
)
_, err := b.wallet.Manager.NewScopedKeyManager(
addrmgrNs, scope, addrSchema,
)
return err
},
)
if err != nil {
return err
}
}
}
scope, err := b.wallet.Manager.FetchScopedKeyManager(b.chainKeyScope)
if err != nil {
// If the scope hasn't yet been created (it wouldn't been
// loaded by default if it was), then we'll manually create the
// scope for the first time ourselves.
err := walletdb.Update(b.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
scope, err = b.wallet.Manager.NewScopedKeyManager(
addrmgrNs, b.chainKeyScope, lightningAddrSchema,
)
return err
})
if err != nil {
return err
}
}
// Now that the wallet is unlocked, we'll go ahead and make sure we
// create accounts for all the key families we're going to use. This
// will make it possible to list all the account/family xpubs in the
// wallet list RPC.
err = walletdb.Update(b.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// Generate all accounts that we could ever need. This includes
// all lnd key families as well as some key families used in
// external liquidity tools.
for keyFam := uint32(1); keyFam <= 255; keyFam++ {
// Otherwise, we'll check if the account already exists,
// if so, we can once again bail early.
_, err := scope.AccountName(addrmgrNs, keyFam)
if err == nil {
continue
}
// If we reach this point, then the account hasn't yet
// been created, so we'll need to create it before we
// can proceed.
err = scope.NewRawAccount(addrmgrNs, keyFam)
if err != nil {
return err
}
}
// If this is the first startup with remote signing and wallet
// migration turned on and the wallet wasn't previously
// migrated, we can do that now that we made sure all accounts
// that we need were derived correctly.
if !walletIsWatchOnly && b.cfg.WatchOnly &&
b.cfg.MigrateWatchOnly {
log.Infof("Migrating wallet to watch-only mode, " +
"purging all private key material")
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
err = b.wallet.Manager.ConvertToWatchingOnly(ns)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
// Establish an RPC connection in addition to starting the goroutines
// in the underlying wallet.
if err := b.chain.Start(); err != nil {
return err
}
// Start the underlying btcwallet core.
b.wallet.Start()
// Pass the rpc client into the wallet so it can sync up to the
// current main chain.
b.wallet.SynchronizeRPC(b.chain)
return nil
}
// Stop signals the wallet for shutdown. Shutdown may entail closing
// any active sockets, database handles, stopping goroutines, etc.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) Stop() error {
b.wallet.Stop()
b.wallet.WaitForShutdown()
b.chain.Stop()
return nil
}
// ConfirmedBalance returns the sum of all the wallet's unspent outputs that
// have at least confs confirmations. If confs is set to zero, then all unspent
// outputs, including those currently in the mempool will be included in the
// final sum. The account parameter serves as a filter to retrieve the balance
// for a specific account. When empty, the confirmed balance of all wallet
// accounts is returned.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) ConfirmedBalance(confs int32,
accountFilter string) (btcutil.Amount, error) {
var balance btcutil.Amount
witnessOutputs, err := b.ListUnspentWitness(
confs, math.MaxInt32, accountFilter,
)
if err != nil {
return 0, err
}
for _, witnessOutput := range witnessOutputs {
balance += witnessOutput.Value
}
return balance, nil
}
// keyScopeForAccountAddr determines the appropriate key scope of an account
// based on its name/address type.
func (b *BtcWallet) keyScopeForAccountAddr(accountName string,
addrType lnwallet.AddressType) (waddrmgr.KeyScope, uint32, error) {
// Map the requested address type to its key scope.
var addrKeyScope waddrmgr.KeyScope
switch addrType {
case lnwallet.WitnessPubKey:
addrKeyScope = waddrmgr.KeyScopeBIP0084
case lnwallet.NestedWitnessPubKey:
addrKeyScope = waddrmgr.KeyScopeBIP0049Plus
case lnwallet.TaprootPubkey:
addrKeyScope = waddrmgr.KeyScopeBIP0086
default:
return waddrmgr.KeyScope{}, 0,
fmt.Errorf("unknown address type")
}
// The default account spans across multiple key scopes, so the
// requested address type should already be valid for this account.
if accountName == lnwallet.DefaultAccountName {
return addrKeyScope, defaultAccount, nil
}
// Otherwise, look up the custom account and if it supports the given
// key scope.
accountNumber, err := b.wallet.AccountNumber(addrKeyScope, accountName)
if err != nil {
return waddrmgr.KeyScope{}, 0, err
}
return addrKeyScope, accountNumber, nil
}
// NewAddress returns the next external or internal address for the wallet
// dictated by the value of the `change` parameter. If change is true, then an
// internal address will be returned, otherwise an external address should be
// returned. The account parameter must be non-empty as it determines which
// account the address should be generated from.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) NewAddress(t lnwallet.AddressType, change bool,
accountName string) (btcutil.Address, error) {
// Addresses cannot be derived from the catch-all imported accounts.
if accountName == waddrmgr.ImportedAddrAccountName {
return nil, errNoImportedAddrGen
}
keyScope, account, err := b.keyScopeForAccountAddr(accountName, t)
if err != nil {
return nil, err
}
if change {
return b.wallet.NewChangeAddress(account, keyScope)
}
return b.wallet.NewAddress(account, keyScope)
}
// LastUnusedAddress returns the last *unused* address known by the wallet. An
// address is unused if it hasn't received any payments. This can be useful in
// UIs in order to continually show the "freshest" address without having to
// worry about "address inflation" caused by continual refreshing. Similar to
// NewAddress it can derive a specified address type, and also optionally a
// change address. The account parameter must be non-empty as it determines
// which account the address should be generated from.
func (b *BtcWallet) LastUnusedAddress(addrType lnwallet.AddressType,
accountName string) (btcutil.Address, error) {
// Addresses cannot be derived from the catch-all imported accounts.
if accountName == waddrmgr.ImportedAddrAccountName {
return nil, errNoImportedAddrGen
}
keyScope, account, err := b.keyScopeForAccountAddr(accountName, addrType)
if err != nil {
return nil, err
}
return b.wallet.CurrentAddress(account, keyScope)
}
// IsOurAddress checks if the passed address belongs to this wallet
//
// This is a part of the WalletController interface.
func (b *BtcWallet) IsOurAddress(a btcutil.Address) bool {
result, err := b.wallet.HaveAddress(a)
return result && (err == nil)
}
// AddressInfo returns the information about an address, if it's known to this
// wallet.
//
// NOTE: This is a part of the WalletController interface.
func (b *BtcWallet) AddressInfo(a btcutil.Address) (waddrmgr.ManagedAddress,
error) {
return b.wallet.AddressInfo(a)
}
// ListAccounts retrieves all accounts belonging to the wallet by default. A
// name and key scope filter can be provided to filter through all of the wallet
// accounts and return only those matching.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) ListAccounts(name string,
keyScope *waddrmgr.KeyScope) ([]*waddrmgr.AccountProperties, error) {
var res []*waddrmgr.AccountProperties
switch {
// If both the name and key scope filters were provided, we'll return
// the existing account matching those.
case name != "" && keyScope != nil:
account, err := b.wallet.AccountPropertiesByName(*keyScope, name)
if err != nil {
return nil, err
}
res = append(res, account)
// Only the name filter was provided.
case name != "" && keyScope == nil:
// If the name corresponds to the default or imported accounts,
// we'll return them for all our supported key scopes.
if name == lnwallet.DefaultAccountName ||
name == waddrmgr.ImportedAddrAccountName {
for _, defaultScope := range LndDefaultKeyScopes {
a, err := b.wallet.AccountPropertiesByName(
defaultScope, name,
)
if err != nil {
return nil, err
}
res = append(res, a)
}
break
}
// In theory, there should be only one custom account for the
// given name. However, due to a lack of check, users could
// create custom accounts with various key scopes. This
// behaviour has been fixed but, we return all potential custom
// accounts with the given name.
for _, scope := range waddrmgr.DefaultKeyScopes {
a, err := b.wallet.AccountPropertiesByName(
scope, name,
)
switch {
case waddrmgr.IsError(err, waddrmgr.ErrAccountNotFound):
continue
// In the specific case of a wallet initialized only by
// importing account xpubs (watch only wallets), it is
// possible that some keyscopes will be 'unknown' by the
// wallet (depending on the xpubs given to initialize
// it). If the keyscope is not found, just skip it.
case waddrmgr.IsError(err, waddrmgr.ErrScopeNotFound):
continue
case err != nil:
return nil, err
}
res = append(res, a)
}
if len(res) == 0 {
return nil, newAccountNotFoundError(name)
}
// Only the key scope filter was provided, so we'll return all accounts
// matching it.
case name == "" && keyScope != nil:
accounts, err := b.wallet.Accounts(*keyScope)
if err != nil {
return nil, err
}
for _, account := range accounts.Accounts {
account := account
res = append(res, &account.AccountProperties)
}
// Neither of the filters were provided, so return all accounts for our
// supported key scopes.
case name == "" && keyScope == nil:
for _, defaultScope := range LndDefaultKeyScopes {
accounts, err := b.wallet.Accounts(defaultScope)
if err != nil {
return nil, err
}
for _, account := range accounts.Accounts {
account := account
res = append(res, &account.AccountProperties)
}
}
accounts, err := b.wallet.Accounts(waddrmgr.KeyScope{
Purpose: keychain.BIP0043Purpose,
Coin: b.cfg.CoinType,
})
if err != nil {
return nil, err
}
for _, account := range accounts.Accounts {
account := account
res = append(res, &account.AccountProperties)
}
}
return res, nil
}
// newAccountNotFoundError returns an error indicating that the manager didn't
// find the specific account. This error is used to be compatible with the old
// 'LookupAccount' behaviour previously used.
func newAccountNotFoundError(name string) error {
str := fmt.Sprintf("account name '%s' not found", name)
return waddrmgr.ManagerError{
ErrorCode: waddrmgr.ErrAccountNotFound,
Description: str,
}
}
// RequiredReserve returns the minimum amount of satoshis that should be
// kept in the wallet in order to fee bump anchor channels if necessary.
// The value scales with the number of public anchor channels but is
// capped at a maximum.
func (b *BtcWallet) RequiredReserve(
numAnchorChans uint32) btcutil.Amount {
anchorChanReservedValue := lnwallet.AnchorChanReservedValue
reserved := btcutil.Amount(numAnchorChans) * anchorChanReservedValue
if reserved > lnwallet.MaxAnchorChanReservedValue {
reserved = lnwallet.MaxAnchorChanReservedValue
}
return reserved
}
// ListAddresses retrieves all the addresses along with their balance. An
// account name filter can be provided to filter through all of the
// wallet accounts and return the addresses of only those matching.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) ListAddresses(name string,
showCustomAccounts bool) (lnwallet.AccountAddressMap, error) {
accounts, err := b.ListAccounts(name, nil)
if err != nil {
return nil, err
}
addresses := make(lnwallet.AccountAddressMap)
addressBalance := make(map[string]btcutil.Amount)
// Retrieve all the unspent ouputs.
outputs, err := b.wallet.ListUnspent(0, math.MaxInt32, "")
if err != nil {
return nil, err
}
// Calculate the total balance of each address.
for _, output := range outputs {
amount, err := btcutil.NewAmount(output.Amount)
if err != nil {
return nil, err
}
addressBalance[output.Address] += amount
}
for _, accntDetails := range accounts {
accntScope := accntDetails.KeyScope
scopedMgr, err := b.wallet.Manager.FetchScopedKeyManager(
accntScope,
)
if err != nil {
return nil, err
}
var managedAddrs []waddrmgr.ManagedAddress
err = walletdb.View(
b.wallet.Database(), func(tx walletdb.ReadTx) error {
managedAddrs = nil
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
return scopedMgr.ForEachAccountAddress(
addrmgrNs, accntDetails.AccountNumber,
func(a waddrmgr.ManagedAddress) error {
managedAddrs = append(
managedAddrs, a,
)
return nil
},
)
},
)
if err != nil {
return nil, err
}
// Only consider those accounts which have addresses.
if len(managedAddrs) == 0 {
continue
}
// All the lnd internal/custom keys for channels and other
// functionality are derived from the same scope. Since they
// aren't really used as addresses and will never have an
// on-chain balance, we'll want to show the public key instead.
isLndCustom := accntScope.Purpose == keychain.BIP0043Purpose
addressProperties := make(
[]lnwallet.AddressProperty, len(managedAddrs),
)
for idx, managedAddr := range managedAddrs {
addr := managedAddr.Address()
addressString := addr.String()
// Hex-encode the compressed public key for custom lnd
// keys, addresses don't make a lot of sense.
var (
pubKey *btcec.PublicKey
derivationPath string
)
pka, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
if ok {
pubKey = pka.PubKey()
// There can be an error in two cases: Either
// the address isn't a managed pubkey address,
// which we already checked above, or the
// address is imported in which case we don't
// know the derivation path, and it will just be
// empty anyway.
_, _, derivationPath, _ =
Bip32DerivationFromAddress(pka)
}
if pubKey != nil && isLndCustom {
addressString = hex.EncodeToString(
pubKey.SerializeCompressed(),
)
}
addressProperties[idx] = lnwallet.AddressProperty{
Address: addressString,
Internal: managedAddr.Internal(),
Balance: addressBalance[addressString],
PublicKey: pubKey,
DerivationPath: derivationPath,
}
}
if accntScope.Purpose != keychain.BIP0043Purpose ||
showCustomAccounts {
addresses[accntDetails] = addressProperties
}
}
return addresses, nil
}
// ImportAccount imports an account backed by an account extended public key.
// The master key fingerprint denotes the fingerprint of the root key
// corresponding to the account public key (also known as the key with
// derivation path m/). This may be required by some hardware wallets for proper
// identification and signing.
//
// The address type can usually be inferred from the key's version, but may be
// required for certain keys to map them into the proper scope.
//
// For custom accounts, we will first check if there is no account with the same
// name (even with a different key scope). No custom account should have various
// key scopes as it will result in non-deterministic behaviour.
//
// For BIP-0044 keys, an address type must be specified as we intend to not
// support importing BIP-0044 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force
// the standard BIP-0049 derivation scheme, while a witness address type will
// force the standard BIP-0084 derivation scheme.
//
// For BIP-0049 keys, an address type must also be specified to make a
// distinction between the standard BIP-0049 address schema (nested witness
// pubkeys everywhere) and our own BIP-0049Plus address schema (nested pubkeys
// externally, witness pubkeys internally).
//
// This is a part of the WalletController interface.
func (b *BtcWallet) ImportAccount(name string, accountPubKey *hdkeychain.ExtendedKey,
masterKeyFingerprint uint32, addrType *waddrmgr.AddressType,
dryRun bool) (*waddrmgr.AccountProperties, []btcutil.Address,
[]btcutil.Address, error) {
// For custom accounts, we first check if there is no existing account
// with the same name.
if name != lnwallet.DefaultAccountName &&
name != waddrmgr.ImportedAddrAccountName {
_, err := b.ListAccounts(name, nil)
if err == nil {
return nil, nil, nil,
fmt.Errorf("account '%s' already exists",
name)
}
if !waddrmgr.IsError(err, waddrmgr.ErrAccountNotFound) {
return nil, nil, nil, err
}
}
if !dryRun {
accountProps, err := b.wallet.ImportAccount(
name, accountPubKey, masterKeyFingerprint, addrType,
)
if err != nil {
return nil, nil, nil, err
}
return accountProps, nil, nil, nil
}
// Derive addresses from both the external and internal branches of the
// account. There's no risk of address inflation as this is only done
// for dry runs.
accountProps, extAddrs, intAddrs, err := b.wallet.ImportAccountDryRun(
name, accountPubKey, masterKeyFingerprint, addrType,
dryRunImportAccountNumAddrs,
)
if err != nil {
return nil, nil, nil, err
}
externalAddrs := make([]btcutil.Address, len(extAddrs))
for i := 0; i < len(extAddrs); i++ {
externalAddrs[i] = extAddrs[i].Address()
}
internalAddrs := make([]btcutil.Address, len(intAddrs))
for i := 0; i < len(intAddrs); i++ {
internalAddrs[i] = intAddrs[i].Address()
}
return accountProps, externalAddrs, internalAddrs, nil
}
// ImportPublicKey imports a single derived public key into the wallet. The
// address type can usually be inferred from the key's version, but in the case
// of legacy versions (xpub, tpub), an address type must be specified as we
// intend to not support importing BIP-44 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) ImportPublicKey(pubKey *btcec.PublicKey,
addrType waddrmgr.AddressType) error {
return b.wallet.ImportPublicKey(pubKey, addrType)
}
// ImportTaprootScript imports a user-provided taproot script into the address
// manager. The imported script will act as a pay-to-taproot address.
func (b *BtcWallet) ImportTaprootScript(scope waddrmgr.KeyScope,
tapscript *waddrmgr.Tapscript) (waddrmgr.ManagedAddress, error) {
// We want to be able to import script addresses into a watch-only
// wallet, which is only possible if we don't encrypt the script with
// the private key encryption key. By specifying the script as being
// "not secret", we can also decrypt the script in a watch-only wallet.
const isSecretScript = false
// Currently, only v1 (Taproot) scripts are supported. We don't even
// know what a v2 witness version would look like at this point.
const witnessVersionTaproot byte = 1
return b.wallet.ImportTaprootScript(
scope, tapscript, nil, witnessVersionTaproot, isSecretScript,
)
}
// SendOutputs funds, signs, and broadcasts a Bitcoin transaction paying out to
// the specified outputs. In the case the wallet has insufficient funds, or the
// outputs are non-standard, a non-nil error will be returned.
//
// NOTE: This method requires the global coin selection lock to be held.
//
// This is a part of the WalletController interface.
func (b *BtcWallet) SendOutputs(outputs []*wire.TxOut,
feeRate chainfee.SatPerKWeight, minConfs int32, label string,
strategy base.CoinSelectionStrategy) (*wire.MsgTx, error) {
// Convert our fee rate from sat/kw to sat/kb since it's required by
// SendOutputs.
feeSatPerKB := btcutil.Amount(feeRate.FeePerKVByte())
// Sanity check outputs.
if len(outputs) < 1 {
return nil, lnwallet.ErrNoOutputs
}
// Sanity check minConfs.
if minConfs < 0 {
return nil, lnwallet.ErrInvalidMinconf
}
return b.wallet.SendOutputs(
outputs, nil, defaultAccount, minConfs, feeSatPerKB,
strategy, label,