forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 24
/
walletkit_server.go
1623 lines (1419 loc) · 47.8 KB
/
walletkit_server.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
//go:build !no_walletrpc
// +build !no_walletrpc
package walletrpc
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
"decred.org/dcrwallet/v4/wallet"
"github.com/decred/dcrd/blockchain/standalone/v2"
"github.com/decred/dcrd/chaincfg/chainhash"
"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/wire"
"github.com/decred/dcrlnd/input"
"github.com/decred/dcrlnd/internal/psbt"
"github.com/decred/dcrlnd/keychain"
"github.com/decred/dcrlnd/labels"
"github.com/decred/dcrlnd/lnrpc"
"github.com/decred/dcrlnd/lnrpc/signrpc"
"github.com/decred/dcrlnd/lnwallet"
"github.com/decred/dcrlnd/lnwallet/chainfee"
"github.com/decred/dcrlnd/lnwallet/dcrwallet"
"github.com/decred/dcrlnd/macaroons"
"github.com/decred/dcrlnd/sweep"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"gopkg.in/macaroon-bakery.v2/bakery"
)
const (
// importedAddrsAccountName is the name of the account with imported
// scripts/pubkeys.
importedAddrsAccountName = "imported"
)
var (
// macaroonOps are the set of capabilities that our minted macaroon (if
// it doesn't already exist) will have.
macaroonOps = []bakery.Op{
{
Entity: "address",
Action: "write",
},
{
Entity: "address",
Action: "read",
},
{
Entity: "onchain",
Action: "write",
},
{
Entity: "onchain",
Action: "read",
},
}
// macPermissions maps RPC calls to the permissions they require.
macPermissions = map[string][]bakery.Op{
"/walletrpc.WalletKit/DeriveNextKey": {{
Entity: "address",
Action: "read",
}},
"/walletrpc.WalletKit/DeriveKey": {{
Entity: "address",
Action: "read",
}},
"/walletrpc.WalletKit/NextAddr": {{
Entity: "address",
Action: "read",
}},
"/walletrpc.WalletKit/PublishTransaction": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/SendOutputs": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/EstimateFee": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/PendingSweeps": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/BumpFee": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/ListSweeps": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/DeriveNextAccount": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/ExportPrivateKey": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/RescanWallet": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/SpendUTXOs": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/GetWalletTx": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/LabelTransaction": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/LeaseOutput": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/ReleaseOutput": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/ListLeases": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/ListUnspent": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/FundPsbt": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/SignPsbt": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/FinalizePsbt": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/ListAccounts": {{
Entity: "onchain",
Action: "read",
}},
"/walletrpc.WalletKit/ImportAccount": {{
Entity: "onchain",
Action: "write",
}},
"/walletrpc.WalletKit/ImportPublicKey": {{
Entity: "onchain",
Action: "write",
}},
}
// DefaultWalletKitMacFilename is the default name of the wallet kit
// macaroon that we expect to find via a file handle within the main
// configuration file in this package.
DefaultWalletKitMacFilename = "walletkit.macaroon"
// LndInternalLockID is the binary representation of the SHA256 hash of
// the string "lnd-internal-lock-id" and is used for UTXO lock leases to
// identify that we ourselves are locking an UTXO, for example when
// giving out a funded PSBT. The ID corresponds to the hex value of
// ede19a92ed321a4705f8a1cccc1d4f6182545d4bb4fae08bd5937831b7e38f98.
LndInternalLockID = lnwallet.LockID{
0xed, 0xe1, 0x9a, 0x92, 0xed, 0x32, 0x1a, 0x47,
0x05, 0xf8, 0xa1, 0xcc, 0xcc, 0x1d, 0x4f, 0x61,
0x82, 0x54, 0x5d, 0x4b, 0xb4, 0xfa, 0xe0, 0x8b,
0xd5, 0x93, 0x78, 0x31, 0xb7, 0xe3, 0x8f, 0x98,
}
)
// ErrZeroLabel is returned when an attempt is made to label a transaction with
// an empty label.
var ErrZeroLabel = errors.New("cannot label transaction with empty label")
// ServerShell is a shell struct holding a reference to the actual sub-server.
// It is used to register the gRPC sub-server with the root server before we
// have the necessary dependencies to populate the actual sub-server.
type ServerShell struct {
WalletKitServer
}
// WalletKit is a sub-RPC server that exposes a tool kit which allows clients
// to execute common wallet operations. This includes requesting new addresses,
// keys (for contracts!), and publishing transactions.
type WalletKit struct {
cfg *Config
}
// A compile time check to ensure that WalletKit fully implements the
// WalletKitServer gRPC service.
var _ WalletKitServer = (*WalletKit)(nil)
// New creates a new instance of the WalletKit sub-RPC server.
func New(cfg *Config) (*WalletKit, lnrpc.MacaroonPerms, error) {
// If the path of the wallet kit macaroon wasn't specified, then we'll
// assume that it's found at the default network directory.
if cfg.WalletKitMacPath == "" {
cfg.WalletKitMacPath = filepath.Join(
cfg.NetworkDir, DefaultWalletKitMacFilename,
)
}
// Now that we know the full path of the wallet kit macaroon, we can
// check to see if we need to create it or not. If stateless_init is set
// then we don't write the macaroons.
macFilePath := cfg.WalletKitMacPath
if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
!lnrpc.FileExists(macFilePath) {
log.Infof("Baking macaroons for WalletKit RPC Server at: %v",
macFilePath)
// At this point, we know that the wallet kit macaroon doesn't
// yet, exist, so we need to create it with the help of the
// main macaroon service.
walletKitMac, err := cfg.MacService.NewMacaroon(
context.Background(), macaroons.DefaultRootKeyID,
macaroonOps...,
)
if err != nil {
return nil, nil, err
}
walletKitMacBytes, err := walletKitMac.M().MarshalBinary()
if err != nil {
return nil, nil, err
}
err = ioutil.WriteFile(macFilePath, walletKitMacBytes, 0644)
if err != nil {
_ = os.Remove(macFilePath)
return nil, nil, err
}
}
walletKit := &WalletKit{
cfg: cfg,
}
return walletKit, macPermissions, nil
}
// Start launches any helper goroutines required for the sub-server to function.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (w *WalletKit) Start() error {
return nil
}
// Stop signals any active goroutines for a graceful closure.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (w *WalletKit) Stop() error {
return nil
}
// Name returns a unique string representation of the sub-server. This can be
// used to identify the sub-server and also de-duplicate them.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (w *WalletKit) Name() string {
return SubServerName
}
// RegisterWithRootServer will be called by the root gRPC server to direct a
// sub RPC server to register itself with the main gRPC root server. Until this
// is called, each sub-server won't be able to have requests routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
// We make sure that we register it with the main gRPC server to ensure
// all our methods are routed properly.
RegisterWalletKitServer(grpcServer, r)
log.Debugf("WalletKit RPC server successfully registered with " +
"root gRPC server")
return nil
}
// RegisterWithRestServer will be called by the root REST mux to direct a sub
// RPC server to register itself with the main REST mux server. Until this is
// called, each sub-server won't be able to have requests routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) RegisterWithRestServer(ctx context.Context,
mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
// We make sure that we register it with the main REST server to ensure
// all our methods are routed properly.
err := RegisterWalletKitHandlerFromEndpoint(ctx, mux, dest, opts)
if err != nil {
log.Errorf("Could not register WalletKit REST server "+
"with root REST server: %v", err)
return err
}
log.Debugf("WalletKit REST server successfully registered with " +
"root REST server")
return nil
}
// CreateSubServer populates the subserver's dependencies using the passed
// SubServerConfigDispatcher. This method should fully initialize the
// sub-server instance, making it ready for action. It returns the macaroon
// permissions that the sub-server wishes to pass on to the root server for all
// methods routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) CreateSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
subServer, macPermissions, err := createNewSubServer(configRegistry)
if err != nil {
return nil, nil, err
}
r.WalletKitServer = subServer
return subServer, macPermissions, nil
}
// ListUnspent returns useful information about each unspent output owned by the
// wallet, as reported by the underlying `ListUnspentWitness`; the information
// returned is: outpoint, amount in satoshis, address, address type,
// scriptPubKey in hex and number of confirmations. The result is filtered to
// contain outputs whose number of confirmations is between a
// minimum and maximum number of confirmations specified by the user, with 0
// meaning unconfirmed.
func (w *WalletKit) ListUnspent(ctx context.Context,
req *ListUnspentRequest) (*ListUnspentResponse, error) {
// Validate the confirmation arguments.
minConfs, maxConfs, err := lnrpc.ParseConfs(req.MinConfs, req.MaxConfs)
if err != nil {
return nil, err
}
// With our arguments validated, we'll query the internal wallet for
// the set of UTXOs that match our query.
//
// We'll acquire the global coin selection lock to ensure there aren't
// any other concurrent processes attempting to lock any UTXOs which may
// be shown available to us.
var utxos []*lnwallet.Utxo
err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
utxos, err = w.cfg.Wallet.ListUnspentWitness(
minConfs, maxConfs, req.Account,
)
return err
})
if err != nil {
return nil, err
}
rpcUtxos, err := lnrpc.MarshalUtxos(utxos, w.cfg.ChainParams)
if err != nil {
return nil, err
}
return &ListUnspentResponse{
Utxos: rpcUtxos,
}, nil
}
// LeaseOutput locks an output to the given ID, preventing it from being
// available for any future coin selection attempts. The absolute time of the
// lock's expiration is returned. The expiration of the lock can be extended by
// successive invocations of this call. Outputs can be unlocked before their
// expiration through `ReleaseOutput`.
//
// If the output is not known, wtxmgr.ErrUnknownOutput is returned. If the
// output has already been locked to a different ID, then
// wtxmgr.ErrOutputAlreadyLocked is returned.
func (w *WalletKit) LeaseOutput(ctx context.Context,
req *LeaseOutputRequest) (*LeaseOutputResponse, error) {
if len(req.Id) != 32 {
return nil, errors.New("id must be 32 random bytes")
}
var lockID lnwallet.LockID
copy(lockID[:], req.Id)
// Don't allow ID's of 32 bytes, but all zeros.
if lockID == (lnwallet.LockID{}) {
return nil, errors.New("id must be 32 random bytes")
}
// Don't allow our internal ID to be used externally for locking. Only
// unlocking is allowed.
if lockID == LndInternalLockID {
return nil, errors.New("reserved id cannot be used")
}
op, err := unmarshallOutPoint(req.Outpoint)
if err != nil {
return nil, err
}
// Use the specified lock duration or fall back to the default.
duration := DefaultLockDuration
if req.ExpirationSeconds != 0 {
duration = time.Duration(req.ExpirationSeconds) * time.Second
}
// Acquire the global coin selection lock to ensure there aren't any
// other concurrent processes attempting to lease the same UTXO.
var expiration time.Time
err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
expiration, err = w.cfg.Wallet.LeaseOutput(
lockID, *op, duration,
)
return err
})
if err != nil {
return nil, err
}
return &LeaseOutputResponse{
Expiration: uint64(expiration.Unix()),
}, nil
}
// ReleaseOutput unlocks an output, allowing it to be available for coin
// selection if it remains unspent. The ID should match the one used to
// originally lock the output.
func (w *WalletKit) ReleaseOutput(ctx context.Context,
req *ReleaseOutputRequest) (*ReleaseOutputResponse, error) {
if len(req.Id) != 32 {
return nil, errors.New("id must be 32 random bytes")
}
var lockID lnwallet.LockID
copy(lockID[:], req.Id)
op, err := unmarshallOutPoint(req.Outpoint)
if err != nil {
return nil, err
}
// Acquire the global coin selection lock to maintain consistency as
// it's acquired when we initially leased the output.
err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
return w.cfg.Wallet.ReleaseOutput(lockID, *op)
})
if err != nil {
return nil, err
}
return &ReleaseOutputResponse{}, nil
}
// ListLeases returns a list of all currently locked utxos.
func (w *WalletKit) ListLeases(ctx context.Context,
req *ListLeasesRequest) (*ListLeasesResponse, error) {
leases, err := w.cfg.Wallet.ListLeasedOutputs()
if err != nil {
return nil, err
}
return &ListLeasesResponse{
LockedUtxos: marshallLeases(leases),
}, nil
}
// DeriveNextKey attempts to derive the *next* key within the key family
// (account in BIP43) specified. This method should return the next external
// child within this branch.
func (w *WalletKit) DeriveNextKey(ctx context.Context,
req *KeyReq) (*signrpc.KeyDescriptor, error) {
nextKeyDesc, err := w.cfg.KeyRing.DeriveNextKey(
keychain.KeyFamily(req.KeyFamily),
)
if err != nil {
return nil, err
}
return &signrpc.KeyDescriptor{
KeyLoc: &signrpc.KeyLocator{
KeyFamily: int32(nextKeyDesc.Family),
KeyIndex: int32(nextKeyDesc.Index),
},
RawKeyBytes: nextKeyDesc.PubKey.SerializeCompressed(),
}, nil
}
// DeriveKey attempts to derive an arbitrary key specified by the passed
// KeyLocator.
func (w *WalletKit) DeriveKey(ctx context.Context,
req *signrpc.KeyLocator) (*signrpc.KeyDescriptor, error) {
keyDesc, err := w.cfg.KeyRing.DeriveKey(keychain.KeyLocator{
Family: keychain.KeyFamily(req.KeyFamily),
Index: uint32(req.KeyIndex),
})
if err != nil {
return nil, err
}
return &signrpc.KeyDescriptor{
KeyLoc: &signrpc.KeyLocator{
KeyFamily: int32(keyDesc.Family),
KeyIndex: int32(keyDesc.Index),
},
RawKeyBytes: keyDesc.PubKey.SerializeCompressed(),
}, nil
}
// NextAddr returns the next unused address within the wallet.
func (w *WalletKit) NextAddr(ctx context.Context,
req *AddrRequest) (*AddrResponse, error) {
account := lnwallet.DefaultAccountName
if req.Account != "" {
account = req.Account
}
addrType := lnwallet.PubKeyHash
if req.Type != AddressType_UNKNOWN {
return nil, fmt.Errorf("only the default address type (0) is supported")
}
addr, err := w.cfg.Wallet.NewAddress(addrType, req.Change, account)
if err != nil {
return nil, err
}
return &AddrResponse{
Addr: addr.String(),
}, nil
}
// Attempts to publish the passed transaction to the network. Once this returns
// without an error, the wallet will continually attempt to re-broadcast the
// transaction on start up, until it enters the chain.
func (w *WalletKit) PublishTransaction(ctx context.Context,
req *Transaction) (*PublishResponse, error) {
switch {
// If the client doesn't specify a transaction, then there's nothing to
// publish.
case len(req.TxHex) == 0:
return nil, fmt.Errorf("must provide a transaction to " +
"publish")
}
tx := &wire.MsgTx{}
txReader := bytes.NewReader(req.TxHex)
if err := tx.Deserialize(txReader); err != nil {
return nil, err
}
label, err := labels.ValidateAPI(req.Label)
if err != nil {
return nil, err
}
err = w.cfg.Wallet.PublishTransaction(tx, label)
if err != nil {
return nil, err
}
return &PublishResponse{}, nil
}
// SendOutputs is similar to the existing sendmany call in Bitcoind, and allows
// the caller to create a transaction that sends to several outputs at once.
// This is ideal when wanting to batch create a set of transactions.
func (w *WalletKit) SendOutputs(ctx context.Context,
req *SendOutputsRequest) (*SendOutputsResponse, error) {
switch {
// If the client didn't specify any outputs to create, then we can't
// proceed .
case len(req.Outputs) == 0:
return nil, fmt.Errorf("must specify at least one output " +
"to create")
}
// Before we can request this transaction to be created, we'll need to
// amp the protos back into the format that the internal wallet will
// recognize.
outputsToCreate := make([]*wire.TxOut, 0, len(req.Outputs))
for _, output := range req.Outputs {
outputsToCreate = append(outputsToCreate, &wire.TxOut{
Value: output.Value,
PkScript: output.PkScript,
})
}
// Then, we'll extract the minimum number of confirmations that each
// output we use to fund the transaction should satisfy.
minConfs, err := lnrpc.ExtractMinConfs(req.MinConfs, req.SpendUnconfirmed)
if err != nil {
return nil, err
}
label, err := labels.ValidateAPI(req.Label)
if err != nil {
return nil, err
}
// Now that we have the outputs mapped, we can request that the wallet
// attempt to create this transaction.
tx, err := w.cfg.Wallet.SendOutputs(
outputsToCreate, chainfee.AtomPerKByte(req.AtomsPerKb), minConfs, label,
req.Account,
)
if err != nil {
return nil, err
}
var b bytes.Buffer
if err := tx.Serialize(&b); err != nil {
return nil, err
}
return &SendOutputsResponse{
RawTx: b.Bytes(),
}, nil
}
// EstimateFee attempts to query the internal fee estimator of the wallet to
// determine the fee (in atom/kB) to attach to a transaction in order to achieve
// the confirmation target.
func (w *WalletKit) EstimateFee(ctx context.Context,
req *EstimateFeeRequest) (*EstimateFeeResponse, error) {
switch {
// A confirmation target of zero doesn't make any sense. Similarly, we
// reject confirmation targets of 1 as they're unreasonable.
case req.ConfTarget == 0 || req.ConfTarget == 1:
return nil, fmt.Errorf("confirmation target must be greater " +
"than 1")
}
atPerKB, err := w.cfg.FeeEstimator.EstimateFeePerKB(
uint32(req.ConfTarget),
)
if err != nil {
return nil, err
}
return &EstimateFeeResponse{
AtomsPerKb: int64(atPerKB),
}, nil
}
// PendingSweeps returns lists of on-chain outputs that lnd is currently
// attempting to sweep within its central batching engine. Outputs with similar
// fee rates are batched together in order to sweep them within a single
// transaction. The fee rate of each sweeping transaction is determined by
// taking the average fee rate of all the outputs it's trying to sweep.
func (w *WalletKit) PendingSweeps(ctx context.Context,
in *PendingSweepsRequest) (*PendingSweepsResponse, error) {
// Retrieve all of the outputs the UtxoSweeper is currently trying to
// sweep.
pendingInputs, err := w.cfg.Sweeper.PendingInputs()
if err != nil {
return nil, err
}
// Convert them into their respective RPC format.
rpcPendingSweeps := make([]*PendingSweep, 0, len(pendingInputs))
for _, pendingInput := range pendingInputs {
var witnessType WitnessType
switch pendingInput.WitnessType {
case input.CommitmentTimeLock:
witnessType = WitnessType_COMMITMENT_TIME_LOCK
case input.CommitmentNoDelay:
witnessType = WitnessType_COMMITMENT_NO_DELAY
case input.CommitmentRevoke:
witnessType = WitnessType_COMMITMENT_REVOKE
case input.HtlcOfferedRevoke:
witnessType = WitnessType_HTLC_OFFERED_REVOKE
case input.HtlcAcceptedRevoke:
witnessType = WitnessType_HTLC_ACCEPTED_REVOKE
case input.HtlcOfferedTimeoutSecondLevel:
witnessType = WitnessType_HTLC_OFFERED_TIMEOUT_SECOND_LEVEL
case input.HtlcAcceptedSuccessSecondLevel:
witnessType = WitnessType_HTLC_ACCEPTED_SUCCESS_SECOND_LEVEL
case input.HtlcOfferedRemoteTimeout:
witnessType = WitnessType_HTLC_OFFERED_REMOTE_TIMEOUT
case input.HtlcAcceptedRemoteSuccess:
witnessType = WitnessType_HTLC_ACCEPTED_REMOTE_SUCCESS
case input.HtlcSecondLevelRevoke:
witnessType = WitnessType_HTLC_SECOND_LEVEL_REVOKE
case input.WitnessKeyHash:
witnessType = WitnessType_WITNESS_KEY_HASH
case input.NestedWitnessKeyHash:
witnessType = WitnessType_NESTED_WITNESS_KEY_HASH
case input.CommitmentAnchor:
witnessType = WitnessType_COMMITMENT_ANCHOR
// Decred-specific.
case input.PublicKeyHash:
witnessType = WitnessType_PUBKEY_HASH
default:
log.Warnf("Unhandled witness type %v for input %v",
pendingInput.WitnessType, pendingInput.OutPoint)
}
op := &lnrpc.OutPoint{
TxidBytes: pendingInput.OutPoint.Hash[:],
OutputIndex: pendingInput.OutPoint.Index,
}
amountAtoms := uint32(pendingInput.Amount)
atomsPerByte := uint32(pendingInput.LastFeeRate / 1000)
broadcastAttempts := uint32(pendingInput.BroadcastAttempts)
nextBroadcastHeight := pendingInput.NextBroadcastHeight
requestedFee := pendingInput.Params.Fee
requestedFeeRate := uint32(requestedFee.FeeRate / 1000)
rpcPendingSweeps = append(rpcPendingSweeps, &PendingSweep{
Outpoint: op,
WitnessType: witnessType,
AmountAtoms: amountAtoms,
AtomsPerByte: atomsPerByte,
BroadcastAttempts: broadcastAttempts,
NextBroadcastHeight: nextBroadcastHeight,
RequestedAtomsPerByte: requestedFeeRate,
RequestedConfTarget: requestedFee.ConfTarget,
Force: pendingInput.Params.Force,
})
}
return &PendingSweepsResponse{
PendingSweeps: rpcPendingSweeps,
}, nil
}
// unmarshallOutPoint converts an outpoint from its lnrpc type to its canonical
// type.
func unmarshallOutPoint(op *lnrpc.OutPoint) (*wire.OutPoint, error) {
if op == nil {
return nil, fmt.Errorf("empty outpoint provided")
}
var hash chainhash.Hash
switch {
case len(op.TxidBytes) == 0 && len(op.TxidStr) == 0:
fallthrough
case len(op.TxidBytes) != 0 && len(op.TxidStr) != 0:
return nil, fmt.Errorf("either TxidBytes or TxidStr must be " +
"specified, but not both")
// The hash was provided as raw bytes.
case len(op.TxidBytes) != 0:
copy(hash[:], op.TxidBytes)
// The hash was provided as a hex-encoded string.
case len(op.TxidStr) != 0:
h, err := chainhash.NewHashFromStr(op.TxidStr)
if err != nil {
return nil, err
}
hash = *h
}
return &wire.OutPoint{
Hash: hash,
Index: op.OutputIndex,
}, nil
}
// BumpFee allows bumping the fee rate of an arbitrary input. A fee preference
// can be expressed either as a specific fee rate or a delta of blocks in which
// the output should be swept on-chain within. If a fee preference is not
// explicitly specified, then an error is returned. The status of the input
// sweep can be checked through the PendingSweeps RPC.
func (w *WalletKit) BumpFee(ctx context.Context,
in *BumpFeeRequest) (*BumpFeeResponse, error) {
// Parse the outpoint from the request.
op, err := unmarshallOutPoint(in.Outpoint)
if err != nil {
return nil, err
}
// Construct the request's fee preference.
atomsPerKB := chainfee.AtomPerKByte(in.AtomsPerByte * 1000)
feePreference := sweep.FeePreference{
ConfTarget: in.TargetConf,
FeeRate: atomsPerKB,
}
// We'll attempt to bump the fee of the input through the UtxoSweeper.
// If it is currently attempting to sweep the input, then it'll simply
// bump its fee, which will result in a replacement transaction (RBF)
// being broadcast. If it is not aware of the input however,
// lnwallet.ErrNotMine is returned.
params := sweep.ParamsUpdate{
Fee: feePreference,
Force: in.Force,
}
_, err = w.cfg.Sweeper.UpdateParams(*op, params)
switch err {
case nil:
return &BumpFeeResponse{}, nil
case lnwallet.ErrNotMine:
break
default:
return nil, err
}
log.Debugf("Attempting to CPFP outpoint %s", op)
// Since we're unable to perform a bump through RBF, we'll assume the
// user is attempting to bump an unconfirmed transaction's fee rate by
// sweeping an output within it under control of the wallet with a
// higher fee rate, essentially performing a Child-Pays-For-Parent
// (CPFP).
//
// We'll gather all of the information required by the UtxoSweeper in
// order to sweep the output.
utxo, err := w.cfg.Wallet.FetchInputInfo(op)
if err != nil {
return nil, err
}
// We're only able to bump the fee of unconfirmed transactions.
if utxo.Confirmations > 0 {
return nil, errors.New("unable to bump fee of a confirmed " +
"transaction")
}
var witnessType input.WitnessType
switch utxo.AddressType {
case lnwallet.PubKeyHash:
witnessType = input.PublicKeyHash
default:
return nil, fmt.Errorf("unknown input witness %v", op)
}
signDesc := &input.SignDescriptor{
Output: &wire.TxOut{
PkScript: utxo.PkScript,
Value: int64(utxo.Value),
},
HashType: txscript.SigHashAll,
}
// We'll use the current height as the height hint since we're dealing
// with an unconfirmed transaction.
_, currentHeight, err := w.cfg.Chain.GetBestBlock()
if err != nil {
return nil, fmt.Errorf("unable to retrieve current height: %v",
err)
}
input := input.NewBaseInput(op, witnessType, signDesc, uint32(currentHeight))
if _, err = w.cfg.Sweeper.SweepInput(input, sweep.Params{Fee: feePreference}); err != nil {
return nil, err
}
return &BumpFeeResponse{}, nil
}
// ListSweeps returns a list of the sweeps that our node has published.
func (w *WalletKit) ListSweeps(ctx context.Context,
in *ListSweepsRequest) (*ListSweepsResponse, error) {
sweeps, err := w.cfg.Sweeper.ListSweeps()
if err != nil {
return nil, err
}
sweepTxns := make(map[string]bool)
for _, sweep := range sweeps {
sweepTxns[sweep.String()] = true
}
// Some of our sweeps could have been replaced by fee, or dropped out
// of the mempool. Here, we lookup our wallet transactions so that we
// can match our list of sweeps against the list of transactions that
// the wallet is still tracking.
transactions, err := w.cfg.Wallet.ListTransactionDetails(
0, dcrwallet.UnconfirmedHeight, lnwallet.DefaultAccountName,
)
if err != nil {
return nil, err
}
var (
txids []string
txDetails []*lnwallet.TransactionDetail
)
for _, tx := range transactions {
_, ok := sweepTxns[tx.Hash.String()]
if !ok {
continue
}
// Add the txid or full tx details depending on whether we want
// verbose output or not.
if in.Verbose {
txDetails = append(txDetails, tx)
} else {
txids = append(txids, tx.Hash.String())
}
}
if in.Verbose {
return &ListSweepsResponse{
Sweeps: &ListSweepsResponse_TransactionDetails{
TransactionDetails: lnrpc.RPCTransactionDetails(
txDetails,
),
},
}, nil
}
return &ListSweepsResponse{
Sweeps: &ListSweepsResponse_TransactionIds{
TransactionIds: &ListSweepsResponse_TransactionIDs{
TransactionIds: txids,
},
},
}, nil
}
func (w *WalletKit) extendedWallet() (lnwallet.ExtendedWalletController, error) {
if ewc, ok := w.cfg.Wallet.(lnwallet.ExtendedWalletController); ok {
return ewc, nil
}
if lnw, ok := w.cfg.Wallet.(*lnwallet.LightningWallet); ok {
if ewc, ok := lnw.WalletController.(lnwallet.ExtendedWalletController); ok {
return ewc, nil
}
}
return nil, fmt.Errorf("underlying WalletController %T not an ExtendedWalletController",
w.cfg.Wallet)
}
// DeriveNextAccount generates the next account of the wallet.
func (w *WalletKit) DeriveNextAccount(_ context.Context, req *DeriveNextAccountRequest) (*DeriveNextAccountResponse, error) {
ewc, err := w.extendedWallet()
if err != nil {
return nil, err
}
return &DeriveNextAccountResponse{}, ewc.DeriveNextAccount(req.Name)
}
// ExportPrivateKey exports a private key that is derived from a wallet address.
func (w *WalletKit) ExportPrivateKey(_ context.Context, req *ExportPrivateKeyRequest) (*ExportPrivateKeyResponse, error) {
ewc, err := w.extendedWallet()
if err != nil {
return nil, err
}
addr, err := stdaddr.DecodeAddress(req.Address, w.cfg.ChainParams)
if err != nil {
return nil, err
}
pk, err := ewc.ExportPrivKey(addr)
if err != nil {
return nil, err
}
wif, err := dcrutil.NewWIF(pk.Serialize(), w.cfg.ChainParams.PrivateKeyID,
dcrec.STEcdsaSecp256k1)
if err != nil {
return nil, err
}
res := &ExportPrivateKeyResponse{
Wif: wif.String(),
}
return res, nil
}
func (w *WalletKit) RescanWallet(req *RescanWalletRequest,
server WalletKit_RescanWalletServer) error {
progressFunc := func(scannedThrough int32) error {