forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 24
/
wallet.go
1349 lines (1185 loc) · 39.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
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 remotedcrwallet
import (
"bytes"
"context"
"fmt"
"io"
"math"
"strings"
"sync"
"sync/atomic"
"time"
pb "decred.org/dcrwallet/v4/rpc/walletrpc"
"decred.org/dcrwallet/v4/wallet"
base "decred.org/dcrwallet/v4/wallet"
"google.golang.org/grpc"
"decred.org/dcrwallet/v4/wallet/txauthor"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrec"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/hdkeychain/v3"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/txscript/v4/sign"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrlnd/btcwalletcompat"
"github.com/decred/dcrlnd/channeldb"
"github.com/decred/dcrlnd/lnwallet"
"github.com/decred/dcrlnd/lnwallet/chainfee"
)
const (
// 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
)
type DcrWallet struct {
// syncedChan is a channel that is closed once the wallet has initially synced
// to the network. It is protected by atomicWalletSynced.
syncedChan chan struct{}
// atomicWalletSynced is an atomic CAS flag (synced = 1) that indicates
// when syncing has completed.
atomicWalletSynced uint32
// conn is the underlying grpc socket connection.
conn *grpc.ClientConn
cfg Config
chainParams *chaincfg.Params
db *channeldb.DB
*remoteWalletKeyRing
branchExtXPriv *hdkeychain.ExtendedKey
branchIntXPriv *hdkeychain.ExtendedKey
// account is the account number which controls onchain funds available
// for use from dcrlnd.
account uint32
// lockedOutpointsMu controls access to lockedOutpoints.
lockedOutpointsMu sync.Mutex
// lockedOutpoints is a list of outputs that the wallet won't use for
// other operations. This is necessary in the driver because grpc
// doesn't provide an entpoint to control this directly in the wallet.
lockedOutpoints map[wire.OutPoint]struct{}
wallet pb.WalletServiceClient
network pb.NetworkServiceClient
ctx context.Context
cancelCtx func()
}
// A compile time check to ensure that DcrWallet implements the
// WalletController interface.
var _ lnwallet.WalletController = (*DcrWallet)(nil)
// Compile time check to ensure that Dcrwallet implements the
// onchainAddrSourcer interface.
var _ (onchainAddrSourcer) = (*DcrWallet)(nil)
func New(cfg Config) (*DcrWallet, error) {
if cfg.Conn == nil {
return nil, fmt.Errorf("conn cannot be empty")
}
// TODO(decred): Check if the node is synced before allowing this to
// proceed.
ctxb := context.Background()
wallet := pb.NewWalletServiceClient(cfg.Conn)
// Unlock the account.
unlockAcctReq := &pb.UnlockAccountRequest{
AccountNumber: uint32(cfg.AccountNumber),
Passphrase: cfg.PrivatePass,
}
_, err := wallet.UnlockAccount(ctxb, unlockAcctReq)
if err != nil {
return nil, fmt.Errorf("unable to unlock account: %v", err)
}
// Obtain the root master priv key from which all LN-related
// keys are derived. By convention, this is a special branch in the
// passed account.
network := pb.NewNetworkServiceClient(cfg.Conn)
req := &pb.GetAccountExtendedPrivKeyRequest{
AccountNumber: uint32(cfg.AccountNumber),
}
resp, err := wallet.GetAccountExtendedPrivKey(ctxb, req)
// Irrespective of the return of GetAccountExtendedPrivKey, re-lock the
// account.
lockAcctReq := &pb.LockAccountRequest{
AccountNumber: uint32(cfg.AccountNumber),
}
_, lockErr := wallet.LockAccount(ctxb, lockAcctReq)
if lockErr != nil {
dcrwLog.Errorf("Error while locking account number %d: %v",
cfg.AccountNumber, lockErr)
}
// And now check if GetAccountExtendedPrivKey returned an error.
if err != nil {
return nil, fmt.Errorf("unable to get master LN account "+
"extended priv key: %v", err)
}
acctXPriv, err := hdkeychain.NewKeyFromString(
resp.AccExtendedPrivKey, cfg.NetParams,
)
if err != nil {
return nil, fmt.Errorf("unable to create account xpriv: %v", err)
}
// Derive and store the account's external and internal extended priv
// keys so that we can redeem funds stored in this account's utxos and
// use them to fund channels, send coins to other nodes, etc.
branchExtXPriv, err := acctXPriv.Child(0)
if err != nil {
return nil, fmt.Errorf("unable to derive the external branch xpriv: %v", err)
}
branchIntXPriv, err := acctXPriv.Child(1)
if err != nil {
return nil, fmt.Errorf("unable to derive the internal branch xpriv: %v", err)
}
// Ensure we don't attempt to use a keyring derived from a different
// account than previously used by comparing the first external public
// key with the one stored in the database.
firstKey, err := branchExtXPriv.Child(0)
if err != nil {
return nil, fmt.Errorf("unable to derive first external key: %v", err)
}
firstPubKeyBytes := firstKey.SerializedPubKey()
if err = cfg.DB.CompareAndStoreAccountID(firstPubKeyBytes); err != nil {
return nil, fmt.Errorf("account number %d failed to generate "+
"previously stored account ID: %v", cfg.AccountNumber, err)
}
ctx, cancelCtx := context.WithCancel(ctxb)
dcrw := &DcrWallet{
account: uint32(cfg.AccountNumber),
syncedChan: make(chan struct{}),
chainParams: cfg.NetParams,
db: cfg.DB,
cfg: cfg,
conn: cfg.Conn,
wallet: wallet,
network: network,
branchExtXPriv: branchExtXPriv,
branchIntXPriv: branchIntXPriv,
lockedOutpoints: make(map[wire.OutPoint]struct{}),
ctx: ctx,
cancelCtx: cancelCtx,
}
// Finally, create the keyring using the conventions for remote
// wallets.
dcrw.remoteWalletKeyRing, err = newRemoteWalletKeyRing(acctXPriv, cfg.DB, dcrw)
if err != nil {
// Sign operations will fail, so signal the error and prevent
// the wallet from considering itself synced (to prevent usage)
return nil, fmt.Errorf("unable to create wallet key ring: %v", err)
}
return dcrw, nil
}
// BackEnd returns the underlying ChainService's name as a string.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) BackEnd() string {
return "remotedcrwallet"
}
// 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 *DcrWallet) Start() error {
b.synced()
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 *DcrWallet) Stop() error {
b.cancelCtx()
return b.conn.Close()
}
// 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.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) ConfirmedBalance(confs int32, accountName string) (dcrutil.Amount, error) {
var acctNb = b.account
if accountName != "" && accountName != lnwallet.DefaultAccountName {
res, err := b.wallet.AccountNumber(context.Background(), &pb.AccountNumberRequest{AccountName: accountName})
if err != nil {
return 0, fmt.Errorf("unknown account named %s: %v", accountName, err)
}
acctNb = res.AccountNumber
}
req := &pb.BalanceRequest{
AccountNumber: acctNb,
RequiredConfirmations: confs,
}
resp, err := b.wallet.Balance(context.Background(), req)
if err != nil {
return 0, err
}
return dcrutil.Amount(resp.Spendable), 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.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) NewAddress(t lnwallet.AddressType, change bool, accountName string) (stdaddr.Address, error) {
switch t {
case lnwallet.PubKeyHash:
// nop
default:
return nil, fmt.Errorf("unknown address type")
}
var acctNb = b.account
if accountName != lnwallet.DefaultAccountName {
res, err := b.wallet.AccountNumber(context.Background(), &pb.AccountNumberRequest{AccountName: accountName})
if err != nil {
return nil, fmt.Errorf("unknown account named %s: %v", accountName, err)
}
acctNb = res.AccountNumber
}
kind := pb.NextAddressRequest_BIP0044_EXTERNAL
if change {
kind = pb.NextAddressRequest_BIP0044_INTERNAL
}
req := &pb.NextAddressRequest{
Kind: kind,
Account: acctNb,
GapPolicy: pb.NextAddressRequest_GAP_POLICY_WRAP,
}
resp, err := b.wallet.NextAddress(context.Background(), req)
if err != nil {
return nil, err
}
addr, err := stdaddr.DecodeAddress(resp.Address, b.chainParams)
if err != nil {
return nil, err
}
return addr, nil
}
// 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.
func (b *DcrWallet) LastUnusedAddress(addrType lnwallet.AddressType, accountName string) (
stdaddr.Address, error) {
switch addrType {
case lnwallet.PubKeyHash:
// nop
default:
return nil, fmt.Errorf("unknown address type")
}
return nil, fmt.Errorf("LastUnusedAddress unimplemented")
}
// IsOurAddress checks if the passed address belongs to this wallet
//
// This is a part of the WalletController interface.
func (b *DcrWallet) IsOurAddress(a stdaddr.Address) bool {
validReq := &pb.ValidateAddressRequest{
Address: a.String(),
}
validResp, err := b.wallet.ValidateAddress(context.Background(), validReq)
if err != nil {
dcrwLog.Errorf("Error validating address to determine "+
"ownership: %v", err)
return false
}
return validResp.IsMine
}
// SendOutputs funds, signs, and broadcasts a Decred 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.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) SendOutputs(outputs []*wire.TxOut,
feeRate chainfee.AtomPerKByte, minConfs int32, label, fromAccount string) (*wire.MsgTx, error) {
ctxb := context.Background()
var acctNb = b.account
if fromAccount != "" && fromAccount != lnwallet.DefaultAccountName {
res, err := b.wallet.AccountNumber(context.Background(), &pb.AccountNumberRequest{AccountName: fromAccount})
if err != nil {
return nil, fmt.Errorf("unknown account named %s: %v", fromAccount, err)
}
acctNb = res.AccountNumber
}
reqOutputs := make([]*pb.ConstructTransactionRequest_Output, len(outputs))
for i, out := range outputs {
dest := &pb.ConstructTransactionRequest_OutputDestination{
Script: out.PkScript,
ScriptVersion: uint32(out.Version),
}
reqOutputs[i] = &pb.ConstructTransactionRequest_Output{
Amount: out.Value,
Destination: dest,
}
}
req := &pb.ConstructTransactionRequest{
SourceAccount: acctNb,
FeePerKb: int32(feeRate),
NonChangeOutputs: reqOutputs,
RequiredConfirmations: minConfs,
}
resp, err := b.wallet.ConstructTransaction(ctxb, req)
if err != nil {
return nil, err
}
tx := new(wire.MsgTx)
err = tx.FromBytes(resp.UnsignedTransaction)
if err != nil {
return nil, err
}
// We need to manually sign the transaction here (instead of passing it
// to SignTransaction) because we don't hang onto the wallet password,
// but we do know the master priv key to the source account and can
// therefore derive the private keys for the individual addresses of
// the selected utxos.
//
// Additionally, we need to retrieve the index of each utxo address to
// know how to derive the private key.
//
// This ends up being harder (and slower) than this needs to be but
// allows us to not have to keep a completely unlocked remote wallet.
// Loop over the inputs which we need to sign.
for i, in := range tx.TxIn {
// Find out the PKScript of the input.
txReq := &pb.GetTransactionRequest{
TransactionHash: in.PreviousOutPoint.Hash[:],
}
txResp, err := b.wallet.GetTransaction(ctxb, txReq)
if err != nil {
return nil, fmt.Errorf("unable to fetch tx: %v", err)
}
var credit *pb.TransactionDetails_Output
for _, c := range txResp.Transaction.Credits {
if c.Index == in.PreviousOutPoint.Index {
credit = c
break
}
}
if credit == nil {
return nil, fmt.Errorf("unable to find pkscript of "+
"prev outpoint %v", in.PreviousOutPoint)
}
pkScript := credit.OutputScript
// Find out the HD index of the address.
validReq := &pb.ValidateAddressRequest{
Address: credit.Address,
}
validResp, err := b.wallet.ValidateAddress(ctxb, validReq)
if err != nil {
return nil, err
}
// Derive the private key that signs this utxo.
branchXPriv := b.branchExtXPriv
if validResp.IsInternal {
branchXPriv = b.branchIntXPriv
}
extPrivKey, err := branchXPriv.Child(validResp.Index)
if err != nil {
return nil, err
}
privKey, err := extPrivKey.SerializedPrivKey()
if err != nil {
return nil, err
}
// Actually sign the input.
sigScript, err := sign.SignatureScript(
tx, i, pkScript, txscript.SigHashAll, privKey,
dcrec.STEcdsaSecp256k1, true,
)
if err != nil {
return nil, err
}
in.SignatureScript = sigScript
}
// Now publish the transaction to the network.
signedTx, err := tx.Bytes()
if err != nil {
return nil, err
}
publishReq := &pb.PublishTransactionRequest{
SignedTransaction: signedTx,
}
_, err = b.wallet.PublishTransaction(ctxb, publishReq)
if err != nil {
return nil, err
}
return tx, nil
}
// CreateSimpleTx creates a Bitcoin transaction paying to the specified
// outputs. The transaction is not broadcasted to the network, but a new change
// address might be created in the wallet database. In the case the wallet has
// insufficient funds, or the outputs are non-standard, an error should be
// returned. This method also takes the target fee expressed in sat/kw that
// should be used when crafting the transaction.
//
// NOTE: The dryRun argument can be set true to create a tx that doesn't alter
// the database. A tx created with this set to true SHOULD NOT be broadcasted.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) CreateSimpleTx(outputs []*wire.TxOut,
feeRate chainfee.AtomPerKByte, minConfs int32, dryRun bool) (*txauthor.AuthoredTx, error) {
// TODO(decred) Review semantics for btcwallet's CreateSimpleTx.
return nil, fmt.Errorf("CreateSimpleTx unimplemented for dcrwallet")
}
// LockOutpoint marks an outpoint as locked meaning it will no longer be deemed
// as eligible for coin selection. Locking outputs are utilized in order to
// avoid race conditions when selecting inputs for usage when funding a
// channel.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) LockOutpoint(o wire.OutPoint) {
b.lockedOutpointsMu.Lock()
b.lockedOutpoints[o] = struct{}{}
b.lockedOutpointsMu.Unlock()
}
// UnlockOutpoint unlocks a previously locked output, marking it eligible for
// coin selection.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) UnlockOutpoint(o wire.OutPoint) {
b.lockedOutpointsMu.Lock()
delete(b.lockedOutpoints, o)
b.lockedOutpointsMu.Unlock()
}
// ListUnspentWitness returns a slice of all the unspent outputs the wallet
// controls which pay to witness programs either directly or indirectly.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) ListUnspentWitness(minConfs, maxConfs int32, accountName string) (
[]*lnwallet.Utxo, error) {
var acctNb = b.account
if accountName != "" && accountName != lnwallet.DefaultAccountName {
res, err := b.wallet.AccountNumber(context.Background(), &pb.AccountNumberRequest{AccountName: accountName})
if err != nil {
return nil, fmt.Errorf("unknown account named %s: %v", accountName, err)
}
acctNb = res.AccountNumber
}
if maxConfs != 0 && maxConfs != math.MaxInt32 {
return nil, fmt.Errorf("maxconfs is not supported")
}
req := &pb.UnspentOutputsRequest{
Account: acctNb,
RequiredConfirmations: minConfs,
}
stream, err := b.wallet.UnspentOutputs(context.Background(), req)
if err != nil {
return nil, err
}
// Decred only supports p2pkh in its wallets.
addressType := lnwallet.PubKeyHash
// Convert to the appropriate format.
utxos := make([]*lnwallet.Utxo, 0)
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
txid, err := chainhash.NewHash(msg.TransactionHash)
if err != nil {
return nil, err
}
// Ensure this utxo hasn't been locked.
outp := wire.OutPoint{
Hash: *txid,
Index: msg.OutputIndex,
Tree: int8(msg.Tree),
}
b.lockedOutpointsMu.Lock()
_, lockedUtxo := b.lockedOutpoints[outp]
b.lockedOutpointsMu.Unlock()
if lockedUtxo {
continue
}
// TODO(decred): Modify UnspentOutputs() grpc call to return
// the confirmation height so that the confirmation count can
// be deduced without having to perform a second rpc call.
txReq := &pb.GetTransactionRequest{
TransactionHash: txid[:],
}
txResp, err := b.wallet.GetTransaction(context.Background(), txReq)
if err != nil {
return nil, err
}
confs := txResp.Confirmations
if confs > maxConfs {
continue
}
utxo := &lnwallet.Utxo{
AddressType: addressType,
Value: dcrutil.Amount(msg.Amount),
PkScript: msg.PkScript,
OutPoint: outp,
Confirmations: int64(confs),
}
utxos = append(utxos, utxo)
}
return utxos, nil
}
// PublishTransaction performs cursory validation (dust checks, etc), then
// finally broadcasts the passed transaction to the Decred network. If
// publishing the transaction fails, an error describing the reason is
// returned (currently ErrDoubleSpend). If the transaction is already
// published to the network (either in the mempool or chain) no error
// will be returned.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) PublishTransaction(tx *wire.MsgTx, label string) error {
rawTx, err := tx.Bytes()
if err != nil {
return err
}
publishReq := &pb.PublishTransactionRequest{
SignedTransaction: rawTx,
}
_, err = b.wallet.PublishTransaction(context.Background(), publishReq)
dcrwLog.Debugf("PublishTransaction(%s): error %v", newLogClosure(
func() string { return tx.TxHash().String() }), err)
if err != nil {
// TODO(decred): review if the string messages are correct.
// Possible convert from checking the message to checking the
// op.
//
// NOTE(decred): These checks were removed upstream due to
// changing the underlying btcwallet semantics on
// PublishTransaction().
if strings.Contains(err.Error(), "already have") {
// Transaction was already in the mempool, do
// not treat as an error. We do this to mimic
// the behaviour of bitcoind, which will not
// return an error if a transaction in the
// mempool is sent again using the
// sendrawtransaction RPC call.
return nil
}
if strings.Contains(err.Error(), "already exists") {
// Transaction was already mined, we don't
// consider this an error.
return nil
}
if strings.Contains(err.Error(), "by double spending") {
// Output was already spent.
return lnwallet.ErrDoubleSpend
}
if strings.Contains(err.Error(), "already spends the same coins") {
// Output was already spent.
return lnwallet.ErrDoubleSpend
}
if strings.Contains(err.Error(), "already spent") {
// Output was already spent.
return lnwallet.ErrDoubleSpend
}
if strings.Contains(err.Error(), "already been spent") {
// Output was already spent.
return lnwallet.ErrDoubleSpend
}
if strings.Contains(err.Error(), "orphan transaction") {
// Transaction is spending either output that
// is missing or already spent.
return lnwallet.ErrDoubleSpend
}
if strings.Contains(err.Error(), "by double spending") {
// Wallet has a conflicting unmined transaction.
return lnwallet.ErrDoubleSpend
}
return err
}
return nil
}
// AbandonDoubleSpends abandons any unconfirmed transaction that also spends
// any of the specified outpoints.
//
// This is part of the WalletController interface.
func (b *DcrWallet) AbandonDoubleSpends(spentOutpoints ...*wire.OutPoint) error {
// Fetch all unconfirmed transactions.
req := &pb.GetTransactionsRequest{
StartingBlockHeight: -1,
EndingBlockHeight: 0,
}
stream, err := b.wallet.GetTransactions(context.Background(), req)
if err != nil {
return err
}
// Make a map of inputs that were spent to speed up lookup.
spent := make(map[wire.OutPoint]struct{}, len(spentOutpoints))
for _, outp := range spentOutpoints {
spent[*outp] = struct{}{}
}
// Now collect all txs that need to be abandoned.
abandon := make(map[chainhash.Hash]struct{}, len(spentOutpoints))
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
for _, tx := range msg.UnminedTransactions {
wireTx := new(wire.MsgTx)
err := wireTx.FromBytes(tx.Transaction)
if err != nil {
dcrwLog.Warnf("Error decoding wallet-provided "+
"tx: %v", err)
continue
}
txh := wireTx.TxHash()
for _, in := range wireTx.TxIn {
if _, isSpent := spent[in.PreviousOutPoint]; !isSpent {
continue
}
// This input was spent. Register this as a tx
// that needs abandoning.
abandon[txh] = struct{}{}
break
}
}
}
// Finally, abandon all transactions.
for txh := range abandon {
dcrwLog.Infof("Abandoning double spent tx %s", txh)
req := &pb.AbandonTransactionRequest{
TransactionHash: txh[:],
}
_, err := b.wallet.AbandonTransaction(context.Background(), req)
if err != nil {
dcrwLog.Warnf("Error abandoning tx %s: %v", txh, err)
}
}
return nil
}
// extractBalanceDelta extracts the net balance delta from the PoV of the
// wallet given a TransactionSummary.
func extractBalanceDelta(
txSummary *pb.TransactionDetails,
tx *wire.MsgTx,
) (dcrutil.Amount, error) {
// For each input we debit the wallet's outflow for this transaction,
// and for each output we credit the wallet's inflow for this
// transaction.
var balanceDelta dcrutil.Amount
for _, input := range txSummary.Debits {
balanceDelta -= dcrutil.Amount(input.PreviousAmount)
}
for _, output := range txSummary.Credits {
balanceDelta += dcrutil.Amount(tx.TxOut[output.Index].Value)
}
return balanceDelta, nil
}
// minedTransactionsToDetails is a helper function which converts a summary
// information about mined transactions to a TransactionDetail.
func minedTransactionsToDetails(
currentHeight int32,
block *pb.BlockDetails,
chainParams *chaincfg.Params,
acctNb uint32,
) ([]*lnwallet.TransactionDetail, error) {
headerHeight := block.Height
blockHash, err := chainhash.NewHash(block.Hash)
if err != nil {
return nil, err
}
details := make([]*lnwallet.TransactionDetail, 0, len(block.Transactions))
for _, tx := range block.Transactions {
if acctNb < math.MaxUint32 {
fromTargetAcct := false
for _, in := range tx.Debits {
fromTargetAcct = fromTargetAcct || in.PreviousAccount == acctNb
}
for _, out := range tx.Credits {
fromTargetAcct = fromTargetAcct || out.Account == acctNb
}
if !fromTargetAcct {
continue
}
}
wireTx := &wire.MsgTx{}
txReader := bytes.NewReader(tx.Transaction)
if err := wireTx.Deserialize(txReader); err != nil {
return nil, err
}
var destAddresses []stdaddr.Address
for _, txOut := range wireTx.TxOut {
_, outAddresses := stdscript.ExtractAddrs(
txOut.Version, txOut.PkScript, chainParams)
destAddresses = append(destAddresses, outAddresses...)
}
txDetail := &lnwallet.TransactionDetail{
Hash: wireTx.TxHash(),
NumConfirmations: currentHeight - headerHeight + 1,
BlockHash: blockHash,
BlockHeight: headerHeight,
Timestamp: block.Timestamp,
TotalFees: tx.Fee,
DestAddresses: destAddresses,
RawTx: tx.Transaction,
}
balanceDelta, err := extractBalanceDelta(tx, wireTx)
if err != nil {
return nil, err
}
txDetail.Value = balanceDelta
details = append(details, txDetail)
}
return details, nil
}
// unminedTransactionsToDetail is a helper function which converts a summary
// for an unconfirmed transaction to a transaction detail.
func unminedTransactionsToDetail(
summary *pb.TransactionDetails,
chainParams *chaincfg.Params,
) (*lnwallet.TransactionDetail, error) {
wireTx := &wire.MsgTx{}
txReader := bytes.NewReader(summary.Transaction)
if err := wireTx.Deserialize(txReader); err != nil {
return nil, err
}
var destAddresses []stdaddr.Address
for _, txOut := range wireTx.TxOut {
_, outAddresses :=
stdscript.ExtractAddrs(txOut.Version,
txOut.PkScript, chainParams)
destAddresses = append(destAddresses, outAddresses...)
}
txDetail := &lnwallet.TransactionDetail{
Hash: wireTx.TxHash(),
TotalFees: summary.Fee,
Timestamp: summary.Timestamp,
DestAddresses: destAddresses,
RawTx: summary.Transaction,
}
balanceDelta, err := extractBalanceDelta(summary, wireTx)
if err != nil {
return nil, err
}
txDetail.Value = balanceDelta
return txDetail, nil
}
// ListTransactionDetails returns a list of all transactions which are
// relevant to the wallet.
//
// This is a part of the WalletController interface.
func (b *DcrWallet) ListTransactionDetails(startHeight,
endHeight int32, accountName string) ([]*lnwallet.TransactionDetail, error) {
// Grab the best block the wallet knows of, we'll use this to calculate
// # of confirmations shortly below.
bestBlockRes, err := b.wallet.BestBlock(context.Background(), &pb.BestBlockRequest{})
if err != nil {
return nil, err
}
currentHeight := int32(bestBlockRes.Height)
var acctNb = b.account
if accountName == "" {
acctNb = math.MaxUint32
} else if accountName != lnwallet.DefaultAccountName {
res, err := b.wallet.AccountNumber(context.Background(), &pb.AccountNumberRequest{AccountName: accountName})
if err != nil {
return nil, fmt.Errorf("unknown account named %s: %v", accountName, err)
}
acctNb = res.AccountNumber
}
req := &pb.GetTransactionsRequest{
StartingBlockHeight: startHeight,
EndingBlockHeight: endHeight,
}
stream, err := b.wallet.GetTransactions(context.Background(), req)
if err != nil {
return nil, err
}
txs := make([]*lnwallet.TransactionDetail, 0)
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if msg.MinedTransactions != nil {
minedTxs, err := minedTransactionsToDetails(currentHeight,
msg.MinedTransactions, b.chainParams, acctNb)
if err != nil {
return nil, err
}
txs = append(txs, minedTxs...)
}
for _, tx := range msg.UnminedTransactions {
if acctNb < math.MaxUint32 {
fromTargetAcct := false
for _, in := range tx.Debits {
fromTargetAcct = fromTargetAcct || in.PreviousAccount == acctNb
}
for _, out := range tx.Credits {
fromTargetAcct = fromTargetAcct || out.Account == acctNb
}
if !fromTargetAcct {
continue
}
}
unminedTx, err := unminedTransactionsToDetail(tx, b.chainParams)
if err != nil {
return nil, err
}
txs = append(txs, unminedTx)
}
}
return txs, nil
}
// txSubscriptionClient encapsulates the transaction notification client from
// the base wallet. Notifications received from the client will be proxied over
// two distinct channels.
type txSubscriptionClient struct {
txClient pb.WalletService_TransactionNotificationsClient
confirmed chan *lnwallet.TransactionDetail
unconfirmed chan *lnwallet.TransactionDetail
wallet pb.WalletServiceClient
chainParams *chaincfg.Params
wg sync.WaitGroup
ctx context.Context
cancel func()
}
// ConfirmedTransactions returns a channel which will be sent on as new
// relevant transactions are confirmed.
//
// This is part of the TransactionSubscription interface.
func (t *txSubscriptionClient) ConfirmedTransactions() chan *lnwallet.TransactionDetail {
return t.confirmed
}
// UnconfirmedTransactions returns a channel which will be sent on as
// new relevant transactions are seen within the network.
//
// This is part of the TransactionSubscription interface.
func (t *txSubscriptionClient) UnconfirmedTransactions() chan *lnwallet.TransactionDetail {
return t.unconfirmed
}
// Cancel finalizes the subscription, cleaning up any resources allocated.
//
// This is part of the TransactionSubscription interface.
func (t *txSubscriptionClient) Cancel() {
t.cancel()
t.wg.Wait()
}
// notificationProxier proxies the notifications received by the underlying
// wallet's notification client to a higher-level TransactionSubscription
// client.
func (t *txSubscriptionClient) notificationProxier() {
defer t.wg.Done()
for {
msg, err := t.txClient.Recv()
if err == io.EOF {
// Cancel() was called.
break
}
if err != nil {
dcrwLog.Errorf("Error during tx subscription: %v", err)
break
}