-
Notifications
You must be signed in to change notification settings - Fork 648
Expand file tree
/
Copy pathdeprecated.go
More file actions
7919 lines (6852 loc) · 232 KB
/
Copy pathdeprecated.go
File metadata and controls
7919 lines (6852 loc) · 232 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
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
//nolint:lll
package wallet
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/address/v2"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/btcutil/v2"
"github.com/btcsuite/btcd/btcutil/v2/hdkeychain"
"github.com/btcsuite/btcd/chaincfg/v2"
"github.com/btcsuite/btcd/chainhash/v2"
"github.com/btcsuite/btcd/psbt/v2"
"github.com/btcsuite/btcd/txscript/v2"
"github.com/btcsuite/btcd/wire/v2"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/internal/prompt"
"github.com/btcsuite/btcwallet/waddrmgr"
kvdb "github.com/btcsuite/btcwallet/wallet/internal/db/kvdb"
"github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcwallet/wallet/txrules"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/btcsuite/btcwallet/walletdb/migration"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/fn/v2"
)
var (
// bucketTxLabels is the name of the label sub bucket of the wtxmgr top
// level bucket that stores the mapping between a txid and a user-defined
// transaction label.
bucketTxLabels = []byte("l")
)
// AccountResult is the result of a ListAccounts query.
type AccountResult struct {
// AccountProperties is the account's properties.
waddrmgr.AccountProperties
// TotalBalance is the total balance of the account.
TotalBalance btcutil.Amount
}
// AccountsResult is the result of a ListAccounts query. It contains a list of
// accounts and the current block height and hash.
type AccountsResult struct {
// Accounts is a list of accounts.
Accounts []AccountResult
// CurrentBlockHash is the hash of the current block.
CurrentBlockHash chainhash.Hash
// CurrentBlockHeight is the height of the current block.
CurrentBlockHeight int32
}
// CreateWithCallback is the same as Create with an added callback that will be
// called in the same transaction the wallet structure is initialized.
//
// Deprecated: This compatibility helper is retained for the legacy loader
// path.
func CreateWithCallback(db walletdb.DB, pubPass, privPass []byte,
rootKey *hdkeychain.ExtendedKey, params *chaincfg.Params,
birthday time.Time, cb func(walletdb.ReadWriteTx) error) error {
return create(
db, pubPass, privPass, rootKey, params, birthday, false, cb,
)
}
// CreateWatchingOnlyWithCallback is the same as CreateWatchingOnly with an
// added callback that will be called in the same transaction the wallet
// structure is initialized.
//
// Deprecated: This compatibility helper is retained for the legacy loader
// path.
func CreateWatchingOnlyWithCallback(db walletdb.DB, pubPass []byte,
params *chaincfg.Params, birthday time.Time,
cb func(walletdb.ReadWriteTx) error) error {
return create(
db, pubPass, nil, nil, params, birthday, true, cb,
)
}
// CreateWatchingOnly creates a new watch-only wallet, writing it to an empty
// database. No root key can be provided as this wallet will be watching only.
// Likewise no private passphrase may be provided either.
//
// Deprecated: This compatibility helper is retained for the legacy loader
// path.
func CreateWatchingOnly(db walletdb.DB, pubPass []byte,
params *chaincfg.Params, birthday time.Time) error {
return create(
db, pubPass, nil, nil, params, birthday, true, nil,
)
}
// create initializes the legacy single-wallet database layout.
func create(db walletdb.DB, pubPass, privPass []byte,
rootKey *hdkeychain.ExtendedKey, params *chaincfg.Params,
birthday time.Time, isWatchingOnly bool,
cb func(walletdb.ReadWriteTx) error) error {
// If no root key was provided, we create one now from a random seed.
// But only if this is not a watching-only wallet where the accounts are
// created individually from their xpubs.
if !isWatchingOnly && rootKey == nil {
hdSeed, err := hdkeychain.GenerateSeed(
hdkeychain.RecommendedSeedLen,
)
if err != nil {
return err
}
// Derive the master extended key from the seed.
rootKey, err = hdkeychain.NewMaster(hdSeed, params)
if err != nil {
return fmt.Errorf("failed to derive master extended key")
}
}
// We need a private key if this isn't a watching only wallet.
if !isWatchingOnly && rootKey != nil && !rootKey.IsPrivate() {
return fmt.Errorf("need extended private key for wallet that is not watching only")
}
return walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs, err := tx.CreateTopLevelBucket(waddrmgrNamespaceKey)
if err != nil {
return err
}
txmgrNs, err := tx.CreateTopLevelBucket(wtxmgrNamespaceKey)
if err != nil {
return err
}
err = waddrmgr.Create(
addrmgrNs, rootKey, pubPass, privPass, params, nil,
birthday,
)
if err != nil {
return err
}
err = wtxmgr.Create(txmgrNs)
if err != nil {
return err
}
if cb != nil {
return cb(tx)
}
return nil
})
}
// RemoveDescendants attempts to remove any transaction from the wallet's tx
// store that spends outputs created by the passed transaction.
//
// Deprecated: This compatibility helper will be removed once tx-writer
// mutations are fully migrated.
func (w *Wallet) RemoveDescendants(tx *wire.MsgTx) error {
txRecord, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now())
if err != nil {
return err
}
return walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
wtxmgrNs := tx.ReadWriteBucket(wtxmgrNamespaceKey)
return w.txStore.RemoveUnminedTx(wtxmgrNs, txRecord)
})
}
// BirthdayBlock returns the birthday block of the wallet.
//
// Deprecated: Use `Controller.Info` instead.
func (w *Wallet) BirthdayBlock() (*waddrmgr.BlockStamp, error) {
var birthdayBlock waddrmgr.BlockStamp
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
bb, _, err := w.addrStore.BirthdayBlock(addrmgrNs)
birthdayBlock = bb
return err
})
if err != nil {
return nil, err
}
return &birthdayBlock, nil
}
// AddrManager returns the internal address manager.
//
// Deprecated: This compatibility helper leaks the legacy address manager.
func (w *Wallet) AddrManager() waddrmgr.AddrStore {
return w.addrStore
}
// NotificationServer returns the internal NotificationServer.
//
// Deprecated: This compatibility helper exposes the legacy notification server.
func (w *Wallet) NotificationServer() *NotificationServer {
return w.NtfnServer
}
// DropTransactionHistory completely removes and re-creates the transaction
// manager namespace from the given wallet database. This can be used to force a
// full chain rescan of all wallet transaction and UTXO data. User-defined
// transaction labels can optionally be kept by setting keepLabels to true.
func DropTransactionHistory(db walletdb.DB, keepLabels bool) error {
log.Infof("Dropping btcwallet transaction history")
err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
// If we want to keep our tx labels, we read them out so we can re-add
// them after we have deleted our wtxmgr.
var (
labels map[chainhash.Hash]string
err error
)
if keepLabels {
labels, err = fetchAllLabels(tx)
if err != nil {
return err
}
}
err = tx.DeleteTopLevelBucket(wtxmgrNamespaceKey)
if err != nil && err != walletdb.ErrBucketNotFound {
return err
}
ns, err := tx.CreateTopLevelBucket(wtxmgrNamespaceKey)
if err != nil {
return err
}
err = wtxmgr.Create(ns)
if err != nil {
return err
}
// If we want to re-add our labels, we do so now.
if keepLabels {
if err := putTxLabels(ns, labels); err != nil {
return err
}
}
ns = tx.ReadWriteBucket(waddrmgrNamespaceKey)
birthdayBlock, err := waddrmgr.FetchBirthdayBlock(ns)
if err != nil {
log.Warnf("Wallet does not have a birthday block set, falling back to rescan from genesis")
startBlock, err := waddrmgr.FetchStartBlock(ns)
if err != nil {
return err
}
return waddrmgr.PutSyncedTo(ns, startBlock)
}
// We'll need to remove our birthday block first because it serves as a
// barrier when updating our state to detect reorgs due to the wallet
// not storing all block hashes of the chain.
if err := waddrmgr.DeleteBirthdayBlock(ns); err != nil {
return err
}
if err := waddrmgr.PutSyncedTo(ns, &birthdayBlock); err != nil {
return err
}
return waddrmgr.PutBirthdayBlock(ns, birthdayBlock)
})
if err != nil {
return fmt.Errorf("failed to drop and re-create namespace: %w", err)
}
return nil
}
// fetchAllLabels returns a map of hex-encoded txid to label.
func fetchAllLabels(tx walletdb.ReadWriteTx) (map[chainhash.Hash]string,
error) {
// Get our top level bucket, if it does not exist we just exit.
txBucket := tx.ReadBucket(wtxmgrNamespaceKey)
if txBucket == nil {
return nil, nil
}
// If we do not have a labels bucket, there are no labels so we exit.
labelsBucket := txBucket.NestedReadBucket(bucketTxLabels)
if labelsBucket == nil {
return nil, nil
}
labels := make(map[chainhash.Hash]string)
if err := labelsBucket.ForEach(func(k, v []byte) error {
txid, err := chainhash.NewHash(k)
if err != nil {
return err
}
label, err := wtxmgr.DeserializeLabel(v)
if err != nil {
return err
}
labels[*txid] = label
return nil
}); err != nil {
return nil, err
}
return labels, nil
}
// putTxLabels re-adds a nested labels bucket and entries to the bucket provided
// if there are any labels present.
func putTxLabels(ns walletdb.ReadWriteBucket,
labels map[chainhash.Hash]string) error {
if len(labels) == 0 {
return nil
}
labelBucket, err := ns.CreateBucketIfNotExists(bucketTxLabels)
if err != nil {
return err
}
for txid, label := range labels {
err := wtxmgr.PutTxLabel(labelBucket, txid, label)
if err != nil {
return err
}
}
return nil
}
// MakeMultiSigScript creates a multi-signature script that can be redeemed with
// nRequired signatures of the passed keys and addresses. If the address is a
// P2PKH address, the associated pubkey is looked up by the wallet if possible,
// otherwise an error is returned for a missing pubkey.
//
// This function only works with pubkeys and P2PKH addresses derived from them.
func (w *Wallet) MakeMultiSigScript(addrs []address.Address,
nRequired int) ([]byte, error) {
pubKeys := make([]*address.AddressPubKey, len(addrs))
var dbtx walletdb.ReadTx
var addrmgrNs walletdb.ReadBucket
defer func() {
if dbtx != nil {
_ = dbtx.Rollback()
}
}()
// The address list will made up either of addresses (pubkey hash), for
// which we need to look up the keys in wallet, straight pubkeys, or a
// mixture of the two.
for i, addr := range addrs {
switch addr := addr.(type) {
default:
return nil, errors.New("cannot make multisig script for a non-secp256k1 public key or P2PKH address")
case *address.AddressPubKey:
pubKeys[i] = addr
case *address.AddressPubKeyHash:
if dbtx == nil {
var err error
dbtx, err = w.cfg.DB.BeginReadTx()
if err != nil {
return nil, err
}
addrmgrNs = dbtx.ReadBucket(waddrmgrNamespaceKey)
}
addrInfo, err := w.addrStore.Address(addrmgrNs, addr)
if err != nil {
return nil, err
}
serializedPubKey := addrInfo.(waddrmgr.ManagedPubKeyAddress).
PubKey().SerializeCompressed()
pubKeyAddr, err := address.NewAddressPubKey(
serializedPubKey, w.cfg.ChainParams,
)
if err != nil {
return nil, err
}
pubKeys[i] = pubKeyAddr
}
}
return txscript.MultiSigScript(pubKeys, nRequired)
}
// ImportP2SHRedeemScript adds a P2SH redeem script to the wallet.
func (w *Wallet) ImportP2SHRedeemScript(script []byte) (*address.AddressScriptHash,
error) {
var p2shAddr *address.AddressScriptHash
err := walletdb.Update(w.cfg.DB, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// TODO(oga) blockstamp current block?
bs := &waddrmgr.BlockStamp{
Hash: *w.ChainParams().GenesisHash,
Height: 0,
}
// As this is a regular P2SH script, we'll import this into the
// BIP0044 scope.
bip44Mgr, err := w.addrStore.FetchScopedKeyManager(
waddrmgr.KeyScopeBIP0084,
)
if err != nil {
return err
}
addrInfo, err := bip44Mgr.ImportScript(addrmgrNs, script, bs)
if err != nil {
// Don't care if it's already there, but still have to set the
// p2shAddr since the address manager didn't return anything
// useful.
if waddrmgr.IsError(err, waddrmgr.ErrDuplicateAddress) {
// This function will never error as it always hashes the
// script to the correct length.
p2shAddr, _ = address.NewAddressScriptHash(
script, w.cfg.ChainParams,
)
return nil
}
return err
}
p2shAddr = addrInfo.Address().(*address.AddressScriptHash)
return nil
})
return p2shAddr, err
}
type unstableAPI struct {
w *Wallet
}
// UnstableAPI exposes additional unstable public APIs for a Wallet. These APIs
// may be changed or removed at any time. Currently this type exists to ease the
// transition, particularly for the legacy JSON-RPC server, from using exported
// manager packages to a unified wallet package that exposes all functionality by
// itself. New code should not be written using this API.
func UnstableAPI(w *Wallet) unstableAPI { return unstableAPI{w} } // nolint:golint
// TxDetails calls wtxmgr.Store.TxDetails under a single database view
// transaction.
func (u unstableAPI) TxDetails(txHash *chainhash.Hash) (*wtxmgr.TxDetails,
error) {
var details *wtxmgr.TxDetails
err := walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
var err error
details, err = u.w.txStore.TxDetails(txmgrNs, txHash)
return err
})
return details, err
}
// RangeTransactions calls wtxmgr.Store.RangeTransactions under a single
// database view transaction.
func (u unstableAPI) RangeTransactions(begin, end int32,
f func([]wtxmgr.TxDetails) (bool, error)) error {
return walletdb.View(u.w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
return u.w.txStore.RangeTransactions(txmgrNs, begin, end, f)
})
}
// NextAccount creates the next account and returns its account number. The
// name must be unique to the account. In order to support automatic seed
// restoring, new accounts may not be created when all of the previous 100
// accounts have no transaction history (this is a deviation from the BIP0044
// spec, which allows no unused account gaps).
func (w *Wallet) NextAccount(scope waddrmgr.KeyScope, name string) (uint32, error) {
manager, err := w.addrStore.FetchScopedKeyManager(scope)
if err != nil {
return 0, err
}
err = manager.CanAddAccountDeprecated()
if err != nil {
return 0, err
}
var (
account uint32
props *waddrmgr.AccountProperties
)
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
account, err = manager.NewAccount(addrmgrNs, name)
if err != nil {
return err
}
props, err = manager.AccountProperties(addrmgrNs, account)
return err
})
if err != nil {
log.Errorf("Cannot fetch new account properties for notification "+
"after account creation: %v", err)
} else {
w.NtfnServer.notifyAccountProperties(props)
}
return account, err
}
// Accounts returns the current names, numbers, and total balances of all
// accounts in the wallet restricted to a particular key scope. The current
// chain tip is included in the result for atomicity reasons.
//
// TODO(jrick): Is the chain tip really needed, since only the total balances
// are included?
func (w *Wallet) Accounts(scope waddrmgr.KeyScope) (*AccountsResult, error) {
manager, err := w.addrStore.FetchScopedKeyManager(scope)
if err != nil {
return nil, err
}
var (
accounts []AccountResult
syncBlockHash *chainhash.Hash
syncBlockHeight int32
)
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.addrStore.SyncedTo()
syncBlockHash = &syncBlock.Hash
syncBlockHeight = syncBlock.Height
unspent, err := w.txStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
err = manager.ForEachAccount(addrmgrNs, func(acct uint32) error {
props, err := manager.AccountProperties(addrmgrNs, acct)
if err != nil {
return err
}
accounts = append(accounts, AccountResult{
AccountProperties: *props,
// TotalBalance set below
})
return nil
})
if err != nil {
return err
}
m := make(map[uint32]*btcutil.Amount)
for i := range accounts {
a := &accounts[i]
m[a.AccountNumber] = &a.TotalBalance
}
for i := range unspent {
output := unspent[i]
var outputAcct uint32
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript, w.chainParams)
if err == nil && len(addrs) > 0 {
_, outputAcct, err = w.addrStore.AddrAccount(addrmgrNs, addrs[0])
}
if err == nil {
amt, ok := m[outputAcct]
if ok {
*amt += output.Amount
}
}
}
return nil
})
return &AccountsResult{
Accounts: accounts,
CurrentBlockHash: *syncBlockHash,
CurrentBlockHeight: syncBlockHeight,
}, err
}
// RenameAccountDeprecated sets the name for an account number to newName.
func (w *Wallet) RenameAccountDeprecated(scope waddrmgr.KeyScope,
account uint32, newName string) error {
manager, err := w.addrStore.FetchScopedKeyManager(scope)
if err != nil {
return err
}
var props *waddrmgr.AccountProperties
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
err := manager.RenameAccount(addrmgrNs, account, newName)
if err != nil {
return err
}
props, err = manager.AccountProperties(addrmgrNs, account)
return err
})
if err == nil {
w.NtfnServer.notifyAccountProperties(props)
}
return err
}
// ScriptForOutputDeprecated returns the address, witness program and redeem
// script for a given UTXO. An error is returned if the UTXO does not
// belong to our wallet or it is not a managed pubKey address.
//
// Deprecated: Use AddressManager.ScriptForOutput instead.
func (w *Wallet) ScriptForOutputDeprecated(output *wire.TxOut) (
waddrmgr.ManagedPubKeyAddress, []byte, []byte, error) {
// First make sure we can sign for the input by making sure the script
// in the UTXO belongs to our wallet and we have the private key for it.
walletAddr, err := w.fetchOutputAddr(output.PkScript)
if err != nil {
return nil, nil, nil, err
}
pubKeyAddr, ok := walletAddr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return nil, nil, nil, fmt.Errorf("address %s is not a "+
"p2wkh or np2wkh address", walletAddr.Address())
}
var (
witnessProgram []byte
sigScript []byte
)
switch {
// If we're spending p2wkh output nested within a p2sh output, then
// we'll need to attach a sigScript in addition to witness data.
case walletAddr.AddrType() == waddrmgr.NestedWitnessPubKey:
pubKey := pubKeyAddr.PubKey()
pubKeyHash := address.Hash160(pubKey.SerializeCompressed())
// Next, we'll generate a valid sigScript that will allow us to
// spend the p2sh output. The sigScript will contain only a
// single push of the p2wkh witness program corresponding to
// the matching public key of this address.
p2wkhAddr, err := address.NewAddressWitnessPubKeyHash(
pubKeyHash, w.chainParams,
)
if err != nil {
return nil, nil, nil, err
}
witnessProgram, err = txscript.PayToAddrScript(p2wkhAddr)
if err != nil {
return nil, nil, nil, err
}
bldr := txscript.NewScriptBuilder()
bldr.AddData(witnessProgram)
sigScript, err = bldr.Script()
if err != nil {
return nil, nil, nil, err
}
// Otherwise, this is a regular p2wkh or p2tr output, so we include the
// witness program itself as the subscript to generate the proper
// sighash digest. As part of the new sighash digest algorithm, the
// p2wkh witness program will be expanded into a regular p2kh
// script.
default:
witnessProgram = output.PkScript
}
return pubKeyAddr, witnessProgram, sigScript, nil
}
// ComputeInputScript generates a complete InputScript for the passed
// transaction with the signature as defined within the passed
// SignDescriptor. This method is capable of generating the proper input
// script for both regular p2wkh output and p2wkh outputs nested within a
// regular p2sh output.
func (w *Wallet) ComputeInputScript(tx *wire.MsgTx, output *wire.TxOut,
inputIndex int, sigHashes *txscript.TxSigHashes,
hashType txscript.SigHashType, tweaker PrivKeyTweaker) (wire.TxWitness,
[]byte, error) {
walletAddr, witnessProgram, sigScript, err :=
w.ScriptForOutputDeprecated(
output,
)
if err != nil {
return nil, nil, err
}
privKey, err := walletAddr.PrivKey()
if err != nil {
return nil, nil, err
}
// If we need to maybe tweak our private key, do it now.
if tweaker != nil {
privKey, err = tweaker(privKey)
if err != nil {
return nil, nil, err
}
}
// We need to produce a Schnorr signature for p2tr key spend addresses.
if txscript.IsPayToTaproot(output.PkScript) {
// We can now generate a valid witness which will allow us to
// spend this output.
witnessScript, err := txscript.TaprootWitnessSignature(
tx, sigHashes, inputIndex, output.Value,
output.PkScript, hashType, privKey,
)
if err != nil {
return nil, nil, err
}
return witnessScript, nil, nil
}
// Generate a valid witness stack for the input.
witnessScript, err := txscript.WitnessSignature(
tx, sigHashes, inputIndex, output.Value, witnessProgram,
hashType, privKey, true,
)
if err != nil {
return nil, nil, err
}
return witnessScript, sigScript, nil
}
var (
// ErrNotMine is an error denoting that a Wallet instance is unable to
// spend a specified output.
ErrNotMine = errors.New("the passed output does not belong to the " +
"wallet")
)
// OutputSelectionPolicy describes the rules for selecting an output from the
// wallet.
type OutputSelectionPolicy struct {
Account uint32
RequiredConfirmations int32
}
func (p *OutputSelectionPolicy) meetsRequiredConfs(txHeight,
curHeight int32) bool {
return hasMinConfs(
//nolint:gosec
uint32(p.RequiredConfirmations), txHeight, curHeight,
)
}
// UnspentOutputs fetches all unspent outputs from the wallet that match rules
// described in the passed policy.
func (w *Wallet) UnspentOutputs(policy OutputSelectionPolicy) ([]*TransactionOutput, error) {
var outputResults []*TransactionOutput
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
syncBlock := w.addrStore.SyncedTo()
// TODO: actually stream outputs from the db instead of fetching
// all of them at once.
outputs, err := w.txStore.UnspentOutputs(txmgrNs)
if err != nil {
return err
}
for _, output := range outputs {
// Ignore outputs that haven't reached the required
// number of confirmations.
if !policy.meetsRequiredConfs(output.Height, syncBlock.Height) {
continue
}
// Ignore outputs that are not controlled by the account.
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript,
w.chainParams)
if err != nil || len(addrs) == 0 {
// Cannot determine which account this belongs
// to without a valid address. TODO: Fix this
// by saving outputs per account, or accounts
// per output.
continue
}
_, outputAcct, err := w.addrStore.AddrAccount(
addrmgrNs, addrs[0],
)
if err != nil {
return err
}
if outputAcct != policy.Account {
continue
}
// Stakebase isn't exposed by wtxmgr so those will be
// OutputKindNormal for now.
outputSource := OutputKindNormal
if output.FromCoinBase {
outputSource = OutputKindCoinbase
}
result := &TransactionOutput{
OutPoint: output.OutPoint,
Output: wire.TxOut{
Value: int64(output.Amount),
PkScript: output.PkScript,
},
OutputKind: outputSource,
ContainingBlock: BlockIdentity(output.Block),
ReceiveTime: output.Received,
}
outputResults = append(outputResults, result)
}
return nil
})
return outputResults, err
}
// FetchInputInfo queries for the wallet's knowledge of the passed outpoint. If
// the wallet determines this output is under its control, then the original
// full transaction, the target txout, the derivation info and the number of
// confirmations are returned. Otherwise, a non-nil error value of ErrNotMine
// is returned instead.
//
// NOTE: This method is kept for compatibility.
func (w *Wallet) FetchInputInfo(prevOut *wire.OutPoint) (*wire.MsgTx,
*wire.TxOut, *psbt.Bip32Derivation, int64, error) {
tx, txOut, confs, err := w.FetchOutpointInfo(prevOut)
if err != nil {
return nil, nil, nil, 0, err
}
derivation, err := w.FetchDerivationInfo(txOut.PkScript)
if err != nil {
return nil, nil, nil, 0, err
}
return tx, txOut, derivation, confs, nil
}
// fetchOutputAddr attempts to fetch the managed address corresponding to the
// passed output script. This function is used to look up the proper key which
// should be used to sign a specified input.
func (w *Wallet) fetchOutputAddr(script []byte) (waddrmgr.ManagedAddress, error) {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(script, w.chainParams)
if err != nil {
return nil, err
}
// If the case of a multi-sig output, several address may be extracted.
// Therefore, we simply select the key for the first address we know
// of.
for _, addr := range addrs {
addr, err := w.AddressInfoDeprecated(addr)
if err == nil {
return addr, nil
}
}
return nil, ErrNotMine
}
// FetchOutpointInfo queries for the wallet's knowledge of the passed outpoint.
// If the wallet determines this output is under its control, the original full
// transaction, the target txout and the number of confirmations are returned.
// Otherwise, a non-nil error value of ErrNotMine is returned instead.
func (w *Wallet) FetchOutpointInfo(prevOut *wire.OutPoint) (*wire.MsgTx,
*wire.TxOut, int64, error) {
// We manually look up the output within the tx store.
txid := &prevOut.Hash
txDetail, err := UnstableAPI(w).TxDetails(txid)
if err != nil {
return nil, nil, 0, err
} else if txDetail == nil {
return nil, nil, 0, ErrNotMine
}
// With the output retrieved, we'll make an additional check to ensure
// we actually have control of this output. We do this because the
// check above only guarantees that the transaction is somehow relevant
// to us, like in the event of us being the sender of the transaction.
numOutputs := uint32(len(txDetail.TxRecord.MsgTx.TxOut))
if prevOut.Index >= numOutputs {
return nil, nil, 0, fmt.Errorf("invalid output index %v for "+
"transaction with %v outputs", prevOut.Index,
numOutputs)
}
// Exit early if the output doesn't belong to our wallet. We know it's
// our UTXO iff the `TxDetails` has a credit record on this output.
if !hasOutput(txDetail, prevOut.Index) {
return nil, nil, 0, ErrNotMine
}
pkScript := txDetail.TxRecord.MsgTx.TxOut[prevOut.Index].PkScript
// Determine the number of confirmations the output currently has.
_, currentHeight, err := w.chainClient.GetBestBlock()
if err != nil {
return nil, nil, 0, fmt.Errorf("unable to retrieve current "+
"height: %w", err)
}
confs := int64(0)
if txDetail.Block.Height != -1 {
confs = int64(currentHeight - txDetail.Block.Height)
}
return &txDetail.TxRecord.MsgTx, &wire.TxOut{
Value: txDetail.TxRecord.MsgTx.TxOut[prevOut.Index].Value,
PkScript: pkScript,
}, confs, nil
}
// FetchDerivationInfo queries for the wallet's knowledge of the passed
// pkScript and constructs the derivation info and returns it.
func (w *Wallet) FetchDerivationInfo(pkScript []byte) (*psbt.Bip32Derivation,
error) {
addr, err := w.fetchOutputAddr(pkScript)
if err != nil {
return nil, err
}
pubKeyAddr, ok := addr.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return nil, ErrNotMine
}
keyScope, derivationPath, _ := pubKeyAddr.DerivationInfo()
derivation := &psbt.Bip32Derivation{
PubKey: pubKeyAddr.PubKey().SerializeCompressed(),
MasterKeyFingerprint: derivationPath.MasterKeyFingerprint,
Bip32Path: []uint32{
keyScope.Purpose + hdkeychain.HardenedKeyStart,
keyScope.Coin + hdkeychain.HardenedKeyStart,
derivationPath.Account,
derivationPath.Branch,
derivationPath.Index,
},
}
return derivation, nil
}
// hasOutpoint takes an output identified by its output index and determines
// whether the TxDetails contains this output. If the TxDetails doesn't have
// this output, it means this output doesn't belong to our wallet.
//
// TODO(yy): implement this method on `TxDetails` and update the package
// `wtxmgr` instead.