• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 16636370523

30 Jul 2025 11:59PM UTC coverage: 66.743% (-0.4%) from 67.181%
16636370523

Pull #10117

github

web-flow
Merge e4c40f1ae into 438906798
Pull Request #10117: contractcourt+sweep: make anchor inputs exclusive

22 of 25 new or added lines in 2 files covered. (88.0%)

927 existing lines in 48 files now uncovered.

134693 of 201808 relevant lines covered (66.74%)

21683.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.83
/lnrpc/walletrpc/walletkit_server.go
1
//go:build walletrpc
2
// +build walletrpc
3

4
package walletrpc
5

6
import (
7
        "bytes"
8
        "context"
9
        "encoding/base64"
10
        "encoding/binary"
11
        "errors"
12
        "fmt"
13
        "maps"
14
        "math"
15
        "os"
16
        "path/filepath"
17
        "slices"
18
        "sort"
19
        "time"
20

21
        "github.com/btcsuite/btcd/btcec/v2"
22
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
23
        "github.com/btcsuite/btcd/btcec/v2/schnorr"
24
        "github.com/btcsuite/btcd/btcutil"
25
        "github.com/btcsuite/btcd/btcutil/hdkeychain"
26
        "github.com/btcsuite/btcd/btcutil/psbt"
27
        "github.com/btcsuite/btcd/chaincfg/chainhash"
28
        "github.com/btcsuite/btcd/txscript"
29
        "github.com/btcsuite/btcd/wire"
30
        "github.com/btcsuite/btcwallet/waddrmgr"
31
        base "github.com/btcsuite/btcwallet/wallet"
32
        "github.com/btcsuite/btcwallet/wtxmgr"
33
        "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
34
        "github.com/lightningnetwork/lnd/channeldb"
35
        "github.com/lightningnetwork/lnd/contractcourt"
36
        "github.com/lightningnetwork/lnd/fn/v2"
37
        "github.com/lightningnetwork/lnd/input"
38
        "github.com/lightningnetwork/lnd/keychain"
39
        "github.com/lightningnetwork/lnd/labels"
40
        "github.com/lightningnetwork/lnd/lnrpc"
41
        "github.com/lightningnetwork/lnd/lnrpc/signrpc"
42
        "github.com/lightningnetwork/lnd/lnwallet"
43
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
44
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
45
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
46
        "github.com/lightningnetwork/lnd/macaroons"
47
        "github.com/lightningnetwork/lnd/sweep"
48
        "google.golang.org/grpc"
49
        "gopkg.in/macaroon-bakery.v2/bakery"
50
)
51

52
var (
53
        // macaroonOps are the set of capabilities that our minted macaroon (if
54
        // it doesn't already exist) will have.
55
        macaroonOps = []bakery.Op{
56
                {
57
                        Entity: "address",
58
                        Action: "write",
59
                },
60
                {
61
                        Entity: "address",
62
                        Action: "read",
63
                },
64
                {
65
                        Entity: "onchain",
66
                        Action: "write",
67
                },
68
                {
69
                        Entity: "onchain",
70
                        Action: "read",
71
                },
72
        }
73

74
        // macPermissions maps RPC calls to the permissions they require.
75
        macPermissions = map[string][]bakery.Op{
76
                "/walletrpc.WalletKit/DeriveNextKey": {{
77
                        Entity: "address",
78
                        Action: "read",
79
                }},
80
                "/walletrpc.WalletKit/DeriveKey": {{
81
                        Entity: "address",
82
                        Action: "read",
83
                }},
84
                "/walletrpc.WalletKit/NextAddr": {{
85
                        Entity: "address",
86
                        Action: "read",
87
                }},
88
                "/walletrpc.WalletKit/GetTransaction": {{
89
                        Entity: "onchain",
90
                        Action: "read",
91
                }},
92
                "/walletrpc.WalletKit/PublishTransaction": {{
93
                        Entity: "onchain",
94
                        Action: "write",
95
                }},
96
                "/walletrpc.WalletKit/SendOutputs": {{
97
                        Entity: "onchain",
98
                        Action: "write",
99
                }},
100
                "/walletrpc.WalletKit/EstimateFee": {{
101
                        Entity: "onchain",
102
                        Action: "read",
103
                }},
104
                "/walletrpc.WalletKit/PendingSweeps": {{
105
                        Entity: "onchain",
106
                        Action: "read",
107
                }},
108
                "/walletrpc.WalletKit/BumpFee": {{
109
                        Entity: "onchain",
110
                        Action: "write",
111
                }},
112
                "/walletrpc.WalletKit/BumpForceCloseFee": {{
113
                        Entity: "onchain",
114
                        Action: "write",
115
                }},
116
                "/walletrpc.WalletKit/ListSweeps": {{
117
                        Entity: "onchain",
118
                        Action: "read",
119
                }},
120
                "/walletrpc.WalletKit/LabelTransaction": {{
121
                        Entity: "onchain",
122
                        Action: "write",
123
                }},
124
                "/walletrpc.WalletKit/LeaseOutput": {{
125
                        Entity: "onchain",
126
                        Action: "write",
127
                }},
128
                "/walletrpc.WalletKit/ReleaseOutput": {{
129
                        Entity: "onchain",
130
                        Action: "write",
131
                }},
132
                "/walletrpc.WalletKit/ListLeases": {{
133
                        Entity: "onchain",
134
                        Action: "read",
135
                }},
136
                "/walletrpc.WalletKit/ListUnspent": {{
137
                        Entity: "onchain",
138
                        Action: "read",
139
                }},
140
                "/walletrpc.WalletKit/ListAddresses": {{
141
                        Entity: "onchain",
142
                        Action: "read",
143
                }},
144
                "/walletrpc.WalletKit/SignMessageWithAddr": {{
145
                        Entity: "onchain",
146
                        Action: "write",
147
                }},
148
                "/walletrpc.WalletKit/VerifyMessageWithAddr": {{
149
                        Entity: "onchain",
150
                        Action: "write",
151
                }},
152
                "/walletrpc.WalletKit/FundPsbt": {{
153
                        Entity: "onchain",
154
                        Action: "write",
155
                }},
156
                "/walletrpc.WalletKit/SignPsbt": {{
157
                        Entity: "onchain",
158
                        Action: "write",
159
                }},
160
                "/walletrpc.WalletKit/FinalizePsbt": {{
161
                        Entity: "onchain",
162
                        Action: "write",
163
                }},
164
                "/walletrpc.WalletKit/ListAccounts": {{
165
                        Entity: "onchain",
166
                        Action: "read",
167
                }},
168
                "/walletrpc.WalletKit/RequiredReserve": {{
169
                        Entity: "onchain",
170
                        Action: "read",
171
                }},
172
                "/walletrpc.WalletKit/ImportAccount": {{
173
                        Entity: "onchain",
174
                        Action: "write",
175
                }},
176
                "/walletrpc.WalletKit/ImportPublicKey": {{
177
                        Entity: "onchain",
178
                        Action: "write",
179
                }},
180
                "/walletrpc.WalletKit/ImportTapscript": {{
181
                        Entity: "onchain",
182
                        Action: "write",
183
                }},
184
                "/walletrpc.WalletKit/RemoveTransaction": {{
185
                        Entity: "onchain",
186
                        Action: "write",
187
                }},
188
        }
189

190
        // DefaultWalletKitMacFilename is the default name of the wallet kit
191
        // macaroon that we expect to find via a file handle within the main
192
        // configuration file in this package.
193
        DefaultWalletKitMacFilename = "walletkit.macaroon"
194

195
        // allWitnessTypes is a mapping between the witness types defined in the
196
        // `input` package, and the witness types in the protobuf definition.
197
        // This map is necessary because the native enum and the protobuf enum
198
        // are numbered differently. The protobuf enum cannot be renumbered
199
        // because this would break backwards compatibility with older clients,
200
        // and the native enum cannot be renumbered because it is stored in the
201
        // watchtower and BreachArbitrator databases.
202
        //
203
        //nolint:ll
204
        allWitnessTypes = map[input.WitnessType]WitnessType{
205
                input.CommitmentTimeLock:                           WitnessType_COMMITMENT_TIME_LOCK,
206
                input.CommitmentNoDelay:                            WitnessType_COMMITMENT_NO_DELAY,
207
                input.CommitmentRevoke:                             WitnessType_COMMITMENT_REVOKE,
208
                input.HtlcOfferedRevoke:                            WitnessType_HTLC_OFFERED_REVOKE,
209
                input.HtlcAcceptedRevoke:                           WitnessType_HTLC_ACCEPTED_REVOKE,
210
                input.HtlcOfferedTimeoutSecondLevel:                WitnessType_HTLC_OFFERED_TIMEOUT_SECOND_LEVEL,
211
                input.HtlcAcceptedSuccessSecondLevel:               WitnessType_HTLC_ACCEPTED_SUCCESS_SECOND_LEVEL,
212
                input.HtlcOfferedRemoteTimeout:                     WitnessType_HTLC_OFFERED_REMOTE_TIMEOUT,
213
                input.HtlcAcceptedRemoteSuccess:                    WitnessType_HTLC_ACCEPTED_REMOTE_SUCCESS,
214
                input.HtlcSecondLevelRevoke:                        WitnessType_HTLC_SECOND_LEVEL_REVOKE,
215
                input.WitnessKeyHash:                               WitnessType_WITNESS_KEY_HASH,
216
                input.NestedWitnessKeyHash:                         WitnessType_NESTED_WITNESS_KEY_HASH,
217
                input.CommitmentAnchor:                             WitnessType_COMMITMENT_ANCHOR,
218
                input.HtlcOfferedTimeoutSecondLevelInputConfirmed:  WitnessType_HTLC_OFFERED_TIMEOUT_SECOND_LEVEL_INPUT_CONFIRMED,
219
                input.HtlcAcceptedSuccessSecondLevelInputConfirmed: WitnessType_HTLC_ACCEPTED_SUCCESS_SECOND_LEVEL_INPUT_CONFIRMED,
220
                input.CommitSpendNoDelayTweakless:                  WitnessType_COMMITMENT_NO_DELAY_TWEAKLESS,
221
                input.CommitmentToRemoteConfirmed:                  WitnessType_COMMITMENT_TO_REMOTE_CONFIRMED,
222
                input.LeaseCommitmentTimeLock:                      WitnessType_LEASE_COMMITMENT_TIME_LOCK,
223
                input.LeaseCommitmentToRemoteConfirmed:             WitnessType_LEASE_COMMITMENT_TO_REMOTE_CONFIRMED,
224
                input.LeaseHtlcOfferedTimeoutSecondLevel:           WitnessType_LEASE_HTLC_OFFERED_TIMEOUT_SECOND_LEVEL,
225
                input.LeaseHtlcAcceptedSuccessSecondLevel:          WitnessType_LEASE_HTLC_ACCEPTED_SUCCESS_SECOND_LEVEL,
226
                input.TaprootPubKeySpend:                           WitnessType_TAPROOT_PUB_KEY_SPEND,
227
                input.TaprootLocalCommitSpend:                      WitnessType_TAPROOT_LOCAL_COMMIT_SPEND,
228
                input.TaprootRemoteCommitSpend:                     WitnessType_TAPROOT_REMOTE_COMMIT_SPEND,
229
                input.TaprootAnchorSweepSpend:                      WitnessType_TAPROOT_ANCHOR_SWEEP_SPEND,
230
                input.TaprootHtlcOfferedTimeoutSecondLevel:         WitnessType_TAPROOT_HTLC_OFFERED_TIMEOUT_SECOND_LEVEL,
231
                input.TaprootHtlcAcceptedSuccessSecondLevel:        WitnessType_TAPROOT_HTLC_ACCEPTED_SUCCESS_SECOND_LEVEL,
232
                input.TaprootHtlcSecondLevelRevoke:                 WitnessType_TAPROOT_HTLC_SECOND_LEVEL_REVOKE,
233
                input.TaprootHtlcAcceptedRevoke:                    WitnessType_TAPROOT_HTLC_ACCEPTED_REVOKE,
234
                input.TaprootHtlcOfferedRevoke:                     WitnessType_TAPROOT_HTLC_OFFERED_REVOKE,
235
                input.TaprootHtlcOfferedRemoteTimeout:              WitnessType_TAPROOT_HTLC_OFFERED_REMOTE_TIMEOUT,
236
                input.TaprootHtlcLocalOfferedTimeout:               WitnessType_TAPROOT_HTLC_LOCAL_OFFERED_TIMEOUT,
237
                input.TaprootHtlcAcceptedRemoteSuccess:             WitnessType_TAPROOT_HTLC_ACCEPTED_REMOTE_SUCCESS,
238
                input.TaprootHtlcAcceptedLocalSuccess:              WitnessType_TAPROOT_HTLC_ACCEPTED_LOCAL_SUCCESS,
239
                input.TaprootCommitmentRevoke:                      WitnessType_TAPROOT_COMMITMENT_REVOKE,
240
        }
241
)
242

243
// ServerShell is a shell struct holding a reference to the actual sub-server.
244
// It is used to register the gRPC sub-server with the root server before we
245
// have the necessary dependencies to populate the actual sub-server.
246
type ServerShell struct {
247
        WalletKitServer
248
}
249

250
// WalletKit is a sub-RPC server that exposes a tool kit which allows clients
251
// to execute common wallet operations. This includes requesting new addresses,
252
// keys (for contracts!), and publishing transactions.
253
type WalletKit struct {
254
        // Required by the grpc-gateway/v2 library for forward compatibility.
255
        UnimplementedWalletKitServer
256

257
        cfg *Config
258
}
259

260
// A compile time check to ensure that WalletKit fully implements the
261
// WalletKitServer gRPC service.
262
var _ WalletKitServer = (*WalletKit)(nil)
263

264
// New creates a new instance of the WalletKit sub-RPC server.
265
func New(cfg *Config) (*WalletKit, lnrpc.MacaroonPerms, error) {
1✔
266
        // If the path of the wallet kit macaroon wasn't specified, then we'll
1✔
267
        // assume that it's found at the default network directory.
1✔
268
        if cfg.WalletKitMacPath == "" {
2✔
269
                cfg.WalletKitMacPath = filepath.Join(
1✔
270
                        cfg.NetworkDir, DefaultWalletKitMacFilename,
1✔
271
                )
1✔
272
        }
1✔
273

274
        // Now that we know the full path of the wallet kit macaroon, we can
275
        // check to see if we need to create it or not. If stateless_init is set
276
        // then we don't write the macaroons.
277
        macFilePath := cfg.WalletKitMacPath
1✔
278
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
1✔
279
                !lnrpc.FileExists(macFilePath) {
2✔
280

1✔
281
                log.Infof("Baking macaroons for WalletKit RPC Server at: %v",
1✔
282
                        macFilePath)
1✔
283

1✔
284
                // At this point, we know that the wallet kit macaroon doesn't
1✔
285
                // yet, exist, so we need to create it with the help of the
1✔
286
                // main macaroon service.
1✔
287
                walletKitMac, err := cfg.MacService.NewMacaroon(
1✔
288
                        context.Background(), macaroons.DefaultRootKeyID,
1✔
289
                        macaroonOps...,
1✔
290
                )
1✔
291
                if err != nil {
1✔
292
                        return nil, nil, err
×
293
                }
×
294
                walletKitMacBytes, err := walletKitMac.M().MarshalBinary()
1✔
295
                if err != nil {
1✔
296
                        return nil, nil, err
×
297
                }
×
298
                err = os.WriteFile(macFilePath, walletKitMacBytes, 0644)
1✔
299
                if err != nil {
1✔
300
                        _ = os.Remove(macFilePath)
×
301
                        return nil, nil, err
×
302
                }
×
303
        }
304

305
        walletKit := &WalletKit{
1✔
306
                cfg: cfg,
1✔
307
        }
1✔
308

1✔
309
        return walletKit, macPermissions, nil
1✔
310
}
311

312
// Start launches any helper goroutines required for the sub-server to function.
313
//
314
// NOTE: This is part of the lnrpc.SubServer interface.
315
func (w *WalletKit) Start() error {
1✔
316
        return nil
1✔
317
}
1✔
318

319
// Stop signals any active goroutines for a graceful closure.
320
//
321
// NOTE: This is part of the lnrpc.SubServer interface.
322
func (w *WalletKit) Stop() error {
1✔
323
        return nil
1✔
324
}
1✔
325

326
// Name returns a unique string representation of the sub-server. This can be
327
// used to identify the sub-server and also de-duplicate them.
328
//
329
// NOTE: This is part of the lnrpc.SubServer interface.
330
func (w *WalletKit) Name() string {
1✔
331
        return SubServerName
1✔
332
}
1✔
333

334
// RegisterWithRootServer will be called by the root gRPC server to direct a
335
// sub RPC server to register itself with the main gRPC root server. Until this
336
// is called, each sub-server won't be able to have requests routed towards it.
337
//
338
// NOTE: This is part of the lnrpc.GrpcHandler interface.
339
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
1✔
340
        // We make sure that we register it with the main gRPC server to ensure
1✔
341
        // all our methods are routed properly.
1✔
342
        RegisterWalletKitServer(grpcServer, r)
1✔
343

1✔
344
        log.Debugf("WalletKit RPC server successfully registered with " +
1✔
345
                "root gRPC server")
1✔
346

1✔
347
        return nil
1✔
348
}
1✔
349

350
// RegisterWithRestServer will be called by the root REST mux to direct a sub
351
// RPC server to register itself with the main REST mux server. Until this is
352
// called, each sub-server won't be able to have requests routed towards it.
353
//
354
// NOTE: This is part of the lnrpc.GrpcHandler interface.
355
func (r *ServerShell) RegisterWithRestServer(ctx context.Context,
356
        mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
1✔
357

1✔
358
        // We make sure that we register it with the main REST server to ensure
1✔
359
        // all our methods are routed properly.
1✔
360
        err := RegisterWalletKitHandlerFromEndpoint(ctx, mux, dest, opts)
1✔
361
        if err != nil {
1✔
362
                log.Errorf("Could not register WalletKit REST server "+
×
363
                        "with root REST server: %v", err)
×
364
                return err
×
365
        }
×
366

367
        log.Debugf("WalletKit REST server successfully registered with " +
1✔
368
                "root REST server")
1✔
369
        return nil
1✔
370
}
371

372
// CreateSubServer populates the subserver's dependencies using the passed
373
// SubServerConfigDispatcher. This method should fully initialize the
374
// sub-server instance, making it ready for action. It returns the macaroon
375
// permissions that the sub-server wishes to pass on to the root server for all
376
// methods routed towards it.
377
//
378
// NOTE: This is part of the lnrpc.GrpcHandler interface.
379
func (r *ServerShell) CreateSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
380
        lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
1✔
381

1✔
382
        subServer, macPermissions, err := createNewSubServer(configRegistry)
1✔
383
        if err != nil {
1✔
384
                return nil, nil, err
×
385
        }
×
386

387
        r.WalletKitServer = subServer
1✔
388
        return subServer, macPermissions, nil
1✔
389
}
390

391
// internalScope returns the internal key scope.
392
func (w *WalletKit) internalScope() waddrmgr.KeyScope {
1✔
393
        return waddrmgr.KeyScope{
1✔
394
                Purpose: keychain.BIP0043Purpose,
1✔
395
                Coin:    w.cfg.ChainParams.HDCoinType,
1✔
396
        }
1✔
397
}
1✔
398

399
// ListUnspent returns useful information about each unspent output owned by
400
// the wallet, as reported by the underlying `ListUnspentWitness`; the
401
// information returned is: outpoint, amount in satoshis, address, address
402
// type, scriptPubKey in hex and number of confirmations. The result is
403
// filtered to contain outputs whose number of confirmations is between a
404
// minimum and maximum number of confirmations specified by the user.
405
func (w *WalletKit) ListUnspent(ctx context.Context,
406
        req *ListUnspentRequest) (*ListUnspentResponse, error) {
1✔
407

1✔
408
        // Force min_confs and max_confs to be zero if unconfirmed_only is
1✔
409
        // true.
1✔
410
        if req.UnconfirmedOnly && (req.MinConfs != 0 || req.MaxConfs != 0) {
1✔
411
                return nil, fmt.Errorf("min_confs and max_confs must be zero " +
×
412
                        "if unconfirmed_only is true")
×
413
        }
×
414

415
        // When unconfirmed_only is inactive and max_confs is zero (default
416
        // values), we will override max_confs to be a MaxInt32, in order
417
        // to return all confirmed and unconfirmed utxos as a default response.
418
        if req.MaxConfs == 0 && !req.UnconfirmedOnly {
2✔
419
                req.MaxConfs = math.MaxInt32
1✔
420
        }
1✔
421

422
        // Validate the confirmation arguments.
423
        minConfs, maxConfs, err := lnrpc.ParseConfs(req.MinConfs, req.MaxConfs)
1✔
424
        if err != nil {
1✔
425
                return nil, err
×
426
        }
×
427

428
        // With our arguments validated, we'll query the internal wallet for
429
        // the set of UTXOs that match our query.
430
        //
431
        // We'll acquire the global coin selection lock to ensure there aren't
432
        // any other concurrent processes attempting to lock any UTXOs which may
433
        // be shown available to us.
434
        var utxos []*lnwallet.Utxo
1✔
435
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
2✔
436
                utxos, err = w.cfg.Wallet.ListUnspentWitness(
1✔
437
                        minConfs, maxConfs, req.Account,
1✔
438
                )
1✔
439

1✔
440
                return err
1✔
441
        })
1✔
442
        if err != nil {
1✔
443
                return nil, err
×
444
        }
×
445

446
        rpcUtxos, err := lnrpc.MarshalUtxos(utxos, w.cfg.ChainParams)
1✔
447
        if err != nil {
1✔
448
                return nil, err
×
449
        }
×
450

451
        return &ListUnspentResponse{
1✔
452
                Utxos: rpcUtxos,
1✔
453
        }, nil
1✔
454
}
455

456
// LeaseOutput locks an output to the given ID, preventing it from being
457
// available for any future coin selection attempts. The absolute time of the
458
// lock's expiration is returned. The expiration of the lock can be extended by
459
// successive invocations of this call. Outputs can be unlocked before their
460
// expiration through `ReleaseOutput`.
461
//
462
// If the output is not known, wtxmgr.ErrUnknownOutput is returned. If the
463
// output has already been locked to a different ID, then
464
// wtxmgr.ErrOutputAlreadyLocked is returned.
465
func (w *WalletKit) LeaseOutput(ctx context.Context,
466
        req *LeaseOutputRequest) (*LeaseOutputResponse, error) {
×
467

×
468
        if len(req.Id) != 32 {
×
469
                return nil, errors.New("id must be 32 random bytes")
×
470
        }
×
471
        var lockID wtxmgr.LockID
×
472
        copy(lockID[:], req.Id)
×
473

×
474
        // Don't allow ID's of 32 bytes, but all zeros.
×
475
        if lockID == (wtxmgr.LockID{}) {
×
476
                return nil, errors.New("id must be 32 random bytes")
×
477
        }
×
478

479
        // Don't allow our internal ID to be used externally for locking. Only
480
        // unlocking is allowed.
481
        if lockID == chanfunding.LndInternalLockID {
×
482
                return nil, errors.New("reserved id cannot be used")
×
483
        }
×
484

485
        op, err := UnmarshallOutPoint(req.Outpoint)
×
486
        if err != nil {
×
487
                return nil, err
×
488
        }
×
489

490
        // Use the specified lock duration or fall back to the default.
491
        duration := chanfunding.DefaultLockDuration
×
492
        if req.ExpirationSeconds != 0 {
×
493
                duration = time.Duration(req.ExpirationSeconds) * time.Second
×
494
        }
×
495

496
        // Acquire the global coin selection lock to ensure there aren't any
497
        // other concurrent processes attempting to lease the same UTXO.
498
        var expiration time.Time
×
499
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
×
500
                expiration, err = w.cfg.Wallet.LeaseOutput(
×
501
                        lockID, *op, duration,
×
502
                )
×
503
                return err
×
504
        })
×
505
        if err != nil {
×
506
                return nil, err
×
507
        }
×
508

509
        return &LeaseOutputResponse{
×
510
                Expiration: uint64(expiration.Unix()),
×
511
        }, nil
×
512
}
513

514
// ReleaseOutput unlocks an output, allowing it to be available for coin
515
// selection if it remains unspent. The ID should match the one used to
516
// originally lock the output.
517
func (w *WalletKit) ReleaseOutput(ctx context.Context,
518
        req *ReleaseOutputRequest) (*ReleaseOutputResponse, error) {
×
519

×
520
        if len(req.Id) != 32 {
×
521
                return nil, errors.New("id must be 32 random bytes")
×
522
        }
×
523
        var lockID wtxmgr.LockID
×
524
        copy(lockID[:], req.Id)
×
525

×
526
        op, err := UnmarshallOutPoint(req.Outpoint)
×
527
        if err != nil {
×
528
                return nil, err
×
529
        }
×
530

531
        // Acquire the global coin selection lock to maintain consistency as
532
        // it's acquired when we initially leased the output.
533
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
×
534
                return w.cfg.Wallet.ReleaseOutput(lockID, *op)
×
535
        })
×
536
        if err != nil {
×
537
                return nil, err
×
538
        }
×
539

540
        return &ReleaseOutputResponse{
×
541
                Status: fmt.Sprintf("output %v released", op.String()),
×
542
        }, nil
×
543
}
544

545
// ListLeases returns a list of all currently locked utxos.
546
func (w *WalletKit) ListLeases(ctx context.Context,
547
        req *ListLeasesRequest) (*ListLeasesResponse, error) {
1✔
548

1✔
549
        leases, err := w.cfg.Wallet.ListLeasedOutputs()
1✔
550
        if err != nil {
1✔
551
                return nil, err
×
552
        }
×
553

554
        return &ListLeasesResponse{
1✔
555
                LockedUtxos: marshallLeases(leases),
1✔
556
        }, nil
1✔
557
}
558

559
// DeriveNextKey attempts to derive the *next* key within the key family
560
// (account in BIP43) specified. This method should return the next external
561
// child within this branch.
562
func (w *WalletKit) DeriveNextKey(ctx context.Context,
563
        req *KeyReq) (*signrpc.KeyDescriptor, error) {
1✔
564

1✔
565
        nextKeyDesc, err := w.cfg.KeyRing.DeriveNextKey(
1✔
566
                keychain.KeyFamily(req.KeyFamily),
1✔
567
        )
1✔
568
        if err != nil {
1✔
569
                return nil, err
×
570
        }
×
571

572
        return &signrpc.KeyDescriptor{
1✔
573
                KeyLoc: &signrpc.KeyLocator{
1✔
574
                        KeyFamily: int32(nextKeyDesc.Family),
1✔
575
                        KeyIndex:  int32(nextKeyDesc.Index),
1✔
576
                },
1✔
577
                RawKeyBytes: nextKeyDesc.PubKey.SerializeCompressed(),
1✔
578
        }, nil
1✔
579
}
580

581
// DeriveKey attempts to derive an arbitrary key specified by the passed
582
// KeyLocator.
583
func (w *WalletKit) DeriveKey(ctx context.Context,
584
        req *signrpc.KeyLocator) (*signrpc.KeyDescriptor, error) {
1✔
585

1✔
586
        keyDesc, err := w.cfg.KeyRing.DeriveKey(keychain.KeyLocator{
1✔
587
                Family: keychain.KeyFamily(req.KeyFamily),
1✔
588
                Index:  uint32(req.KeyIndex),
1✔
589
        })
1✔
590
        if err != nil {
1✔
591
                return nil, err
×
592
        }
×
593

594
        return &signrpc.KeyDescriptor{
1✔
595
                KeyLoc: &signrpc.KeyLocator{
1✔
596
                        KeyFamily: int32(keyDesc.Family),
1✔
597
                        KeyIndex:  int32(keyDesc.Index),
1✔
598
                },
1✔
599
                RawKeyBytes: keyDesc.PubKey.SerializeCompressed(),
1✔
600
        }, nil
1✔
601
}
602

603
// NextAddr returns the next unused address within the wallet.
604
func (w *WalletKit) NextAddr(ctx context.Context,
605
        req *AddrRequest) (*AddrResponse, error) {
1✔
606

1✔
607
        account := lnwallet.DefaultAccountName
1✔
608
        if req.Account != "" {
1✔
609
                account = req.Account
×
610
        }
×
611

612
        addrType := lnwallet.WitnessPubKey
1✔
613
        switch req.Type {
1✔
614
        case AddressType_NESTED_WITNESS_PUBKEY_HASH:
×
615
                addrType = lnwallet.NestedWitnessPubKey
×
616

617
        case AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
×
618
                return nil, fmt.Errorf("invalid address type for next "+
×
619
                        "address: %v", req.Type)
×
620

621
        case AddressType_TAPROOT_PUBKEY:
×
622
                addrType = lnwallet.TaprootPubkey
×
623
        }
624

625
        addr, err := w.cfg.Wallet.NewAddress(addrType, req.Change, account)
1✔
626
        if err != nil {
1✔
627
                return nil, err
×
628
        }
×
629

630
        return &AddrResponse{
1✔
631
                Addr: addr.String(),
1✔
632
        }, nil
1✔
633
}
634

635
// GetTransaction returns a transaction from the wallet given its hash.
636
func (w *WalletKit) GetTransaction(_ context.Context,
637
        req *GetTransactionRequest) (*lnrpc.Transaction, error) {
1✔
638

1✔
639
        // If the client doesn't specify a hash, then there's nothing to
1✔
640
        // return.
1✔
641
        if req.Txid == "" {
1✔
642
                return nil, fmt.Errorf("must provide a transaction hash")
×
643
        }
×
644

645
        txHash, err := chainhash.NewHashFromStr(req.Txid)
1✔
646
        if err != nil {
1✔
647
                return nil, err
×
648
        }
×
649

650
        res, err := w.cfg.Wallet.GetTransactionDetails(txHash)
1✔
651
        if err != nil {
1✔
652
                return nil, err
×
653
        }
×
654

655
        return lnrpc.RPCTransaction(res), nil
1✔
656
}
657

658
// Attempts to publish the passed transaction to the network. Once this returns
659
// without an error, the wallet will continually attempt to re-broadcast the
660
// transaction on start up, until it enters the chain.
661
func (w *WalletKit) PublishTransaction(ctx context.Context,
662
        req *Transaction) (*PublishResponse, error) {
1✔
663

1✔
664
        switch {
1✔
665
        // If the client doesn't specify a transaction, then there's nothing to
666
        // publish.
667
        case len(req.TxHex) == 0:
×
668
                return nil, fmt.Errorf("must provide a transaction to " +
×
669
                        "publish")
×
670
        }
671

672
        tx := &wire.MsgTx{}
1✔
673
        txReader := bytes.NewReader(req.TxHex)
1✔
674
        if err := tx.Deserialize(txReader); err != nil {
1✔
675
                return nil, err
×
676
        }
×
677

678
        label, err := labels.ValidateAPI(req.Label)
1✔
679
        if err != nil {
1✔
680
                return nil, err
×
681
        }
×
682

683
        err = w.cfg.Wallet.PublishTransaction(tx, label)
1✔
684
        if err != nil {
1✔
685
                return nil, err
×
686
        }
×
687

688
        return &PublishResponse{}, nil
1✔
689
}
690

691
// RemoveTransaction attempts to remove the transaction and all of its
692
// descendants resulting from further spends of the outputs of the provided
693
// transaction id.
694
// NOTE: We do not remove the transaction from the rebroadcaster which might
695
// run in the background rebroadcasting not yet confirmed transactions. We do
696
// not have access to the rebroadcaster here nor should we. This command is not
697
// a way to remove transactions from the network. It is a way to shortcircuit
698
// wallet utxo housekeeping while transactions are still unconfirmed and we know
699
// that a transaction will never confirm because a replacement already pays
700
// higher fees.
701
func (w *WalletKit) RemoveTransaction(_ context.Context,
702
        req *GetTransactionRequest) (*RemoveTransactionResponse, error) {
1✔
703

1✔
704
        // If the client doesn't specify a hash, then there's nothing to
1✔
705
        // return.
1✔
706
        if req.Txid == "" {
1✔
707
                return nil, fmt.Errorf("must provide a transaction hash")
×
708
        }
×
709

710
        txHash, err := chainhash.NewHashFromStr(req.Txid)
1✔
711
        if err != nil {
1✔
712
                return nil, err
×
713
        }
×
714

715
        // Query the tx store of our internal wallet for the specified
716
        // transaction.
717
        res, err := w.cfg.Wallet.GetTransactionDetails(txHash)
1✔
718
        if err != nil {
1✔
719
                return nil, fmt.Errorf("transaction with txid=%v not found "+
×
720
                        "in the internal wallet store", txHash)
×
721
        }
×
722

723
        // Only allow unconfirmed transactions to be removed because as soon
724
        // as a transaction is confirmed it will be evaluated by the wallet
725
        // again and the wallet state would be updated in case the user had
726
        // removed the transaction accidentally.
727
        if res.NumConfirmations > 0 {
1✔
728
                return nil, fmt.Errorf("transaction with txid=%v is already "+
×
729
                        "confirmed (numConfs=%d) cannot be removed", txHash,
×
730
                        res.NumConfirmations)
×
731
        }
×
732

733
        tx := &wire.MsgTx{}
1✔
734
        txReader := bytes.NewReader(res.RawTx)
1✔
735
        if err := tx.Deserialize(txReader); err != nil {
1✔
736
                return nil, err
×
737
        }
×
738

739
        err = w.cfg.Wallet.RemoveDescendants(tx)
1✔
740
        if err != nil {
1✔
741
                return nil, err
×
742
        }
×
743

744
        return &RemoveTransactionResponse{
1✔
745
                Status: "Successfully removed transaction",
1✔
746
        }, nil
1✔
747
}
748

749
// SendOutputs is similar to the existing sendmany call in Bitcoind, and allows
750
// the caller to create a transaction that sends to several outputs at once.
751
// This is ideal when wanting to batch create a set of transactions.
752
func (w *WalletKit) SendOutputs(ctx context.Context,
753
        req *SendOutputsRequest) (*SendOutputsResponse, error) {
1✔
754

1✔
755
        switch {
1✔
756
        // If the client didn't specify any outputs to create, then  we can't
757
        // proceed .
758
        case len(req.Outputs) == 0:
×
759
                return nil, fmt.Errorf("must specify at least one output " +
×
760
                        "to create")
×
761
        }
762

763
        // Before we can request this transaction to be created, we'll need to
764
        // amp the protos back into the format that the internal wallet will
765
        // recognize.
766
        var totalOutputValue int64
1✔
767
        outputsToCreate := make([]*wire.TxOut, 0, len(req.Outputs))
1✔
768
        for _, output := range req.Outputs {
2✔
769
                outputsToCreate = append(outputsToCreate, &wire.TxOut{
1✔
770
                        Value:    output.Value,
1✔
771
                        PkScript: output.PkScript,
1✔
772
                })
1✔
773
                totalOutputValue += output.Value
1✔
774
        }
1✔
775

776
        // Then, we'll extract the minimum number of confirmations that each
777
        // output we use to fund the transaction should satisfy.
778
        minConfs, err := lnrpc.ExtractMinConfs(
1✔
779
                req.MinConfs, req.SpendUnconfirmed,
1✔
780
        )
1✔
781
        if err != nil {
1✔
782
                return nil, err
×
783
        }
×
784

785
        // Before sending out funds we need to ensure that the remainder of our
786
        // wallet funds would cover for the anchor reserve requirement. We'll
787
        // also take unconfirmed funds into account.
788
        walletBalance, err := w.cfg.Wallet.ConfirmedBalance(
1✔
789
                0, lnwallet.DefaultAccountName,
1✔
790
        )
1✔
791
        if err != nil {
1✔
792
                return nil, err
×
793
        }
×
794

795
        // We'll get the currently required reserve amount.
796
        reserve, err := w.RequiredReserve(ctx, &RequiredReserveRequest{})
1✔
797
        if err != nil {
1✔
798
                return nil, err
×
799
        }
×
800

801
        // Then we check if our current wallet balance undershoots the required
802
        // reserve if we'd send out the outputs specified in the request.
803
        if int64(walletBalance)-totalOutputValue < reserve.RequiredReserve {
2✔
804
                return nil, ErrInsufficientReserve
1✔
805
        }
1✔
806

807
        label, err := labels.ValidateAPI(req.Label)
1✔
808
        if err != nil {
1✔
809
                return nil, err
×
810
        }
×
811

812
        coinSelectionStrategy, err := lnrpc.UnmarshallCoinSelectionStrategy(
1✔
813
                req.CoinSelectionStrategy, w.cfg.CoinSelectionStrategy,
1✔
814
        )
1✔
815
        if err != nil {
1✔
816
                return nil, err
×
817
        }
×
818

819
        // Now that we have the outputs mapped and checked for the reserve
820
        // requirement, we can request that the wallet attempts to create this
821
        // transaction.
822
        tx, err := w.cfg.Wallet.SendOutputs(
1✔
823
                nil, outputsToCreate, chainfee.SatPerKWeight(req.SatPerKw),
1✔
824
                minConfs, label, coinSelectionStrategy,
1✔
825
        )
1✔
826
        if err != nil {
1✔
827
                return nil, err
×
828
        }
×
829

830
        var b bytes.Buffer
1✔
831
        if err := tx.Serialize(&b); err != nil {
1✔
832
                return nil, err
×
833
        }
×
834

835
        return &SendOutputsResponse{
1✔
836
                RawTx: b.Bytes(),
1✔
837
        }, nil
1✔
838
}
839

840
// EstimateFee attempts to query the internal fee estimator of the wallet to
841
// determine the fee (in sat/kw) to attach to a transaction in order to achieve
842
// the confirmation target.
843
func (w *WalletKit) EstimateFee(ctx context.Context,
844
        req *EstimateFeeRequest) (*EstimateFeeResponse, error) {
×
845

×
846
        switch {
×
847
        // A confirmation target of zero doesn't make any sense. Similarly, we
848
        // reject confirmation targets of 1 as they're unreasonable.
849
        case req.ConfTarget == 0 || req.ConfTarget == 1:
×
850
                return nil, fmt.Errorf("confirmation target must be greater " +
×
851
                        "than 1")
×
852
        }
853

854
        satPerKw, err := w.cfg.FeeEstimator.EstimateFeePerKW(
×
855
                uint32(req.ConfTarget),
×
856
        )
×
857
        if err != nil {
×
858
                return nil, err
×
859
        }
×
860

861
        relayFeePerKw := w.cfg.FeeEstimator.RelayFeePerKW()
×
862

×
863
        return &EstimateFeeResponse{
×
864
                SatPerKw:            int64(satPerKw),
×
865
                MinRelayFeeSatPerKw: int64(relayFeePerKw),
×
866
        }, nil
×
867
}
868

869
// PendingSweeps returns lists of on-chain outputs that lnd is currently
870
// attempting to sweep within its central batching engine. Outputs with similar
871
// fee rates are batched together in order to sweep them within a single
872
// transaction. The fee rate of each sweeping transaction is determined by
873
// taking the average fee rate of all the outputs it's trying to sweep.
874
func (w *WalletKit) PendingSweeps(ctx context.Context,
875
        in *PendingSweepsRequest) (*PendingSweepsResponse, error) {
1✔
876

1✔
877
        // Retrieve all of the outputs the UtxoSweeper is currently trying to
1✔
878
        // sweep.
1✔
879
        inputsMap, err := w.cfg.Sweeper.PendingInputs()
1✔
880
        if err != nil {
1✔
881
                return nil, err
×
882
        }
×
883

884
        // Convert them into their respective RPC format.
885
        rpcPendingSweeps := make([]*PendingSweep, 0, len(inputsMap))
1✔
886
        for _, inp := range inputsMap {
2✔
887
                witnessType, ok := allWitnessTypes[inp.WitnessType]
1✔
888
                if !ok {
1✔
889
                        return nil, fmt.Errorf("unhandled witness type %v for "+
×
890
                                "input %v", inp.WitnessType, inp.OutPoint)
×
891
                }
×
892

893
                op := lnrpc.MarshalOutPoint(&inp.OutPoint)
1✔
894
                amountSat := uint32(inp.Amount)
1✔
895
                satPerVbyte := uint64(inp.LastFeeRate.FeePerVByte())
1✔
896
                broadcastAttempts := uint32(inp.BroadcastAttempts)
1✔
897

1✔
898
                // Get the requested starting fee rate, if set.
1✔
899
                startingFeeRate := fn.MapOptionZ(
1✔
900
                        inp.Params.StartingFeeRate,
1✔
901
                        func(feeRate chainfee.SatPerKWeight) uint64 {
2✔
902
                                return uint64(feeRate.FeePerVByte())
1✔
903
                        })
1✔
904

905
                ps := &PendingSweep{
1✔
906
                        Outpoint:             op,
1✔
907
                        WitnessType:          witnessType,
1✔
908
                        AmountSat:            amountSat,
1✔
909
                        SatPerVbyte:          satPerVbyte,
1✔
910
                        BroadcastAttempts:    broadcastAttempts,
1✔
911
                        Immediate:            inp.Params.Immediate,
1✔
912
                        Budget:               uint64(inp.Params.Budget),
1✔
913
                        DeadlineHeight:       inp.DeadlineHeight,
1✔
914
                        RequestedSatPerVbyte: startingFeeRate,
1✔
915
                        MaturityHeight:       inp.MaturityHeight,
1✔
916
                }
1✔
917
                rpcPendingSweeps = append(rpcPendingSweeps, ps)
1✔
918
        }
919

920
        return &PendingSweepsResponse{
1✔
921
                PendingSweeps: rpcPendingSweeps,
1✔
922
        }, nil
1✔
923
}
924

925
// UnmarshallOutPoint converts an outpoint from its lnrpc type to its canonical
926
// type.
927
func UnmarshallOutPoint(op *lnrpc.OutPoint) (*wire.OutPoint, error) {
1✔
928
        if op == nil {
1✔
929
                return nil, fmt.Errorf("empty outpoint provided")
×
930
        }
×
931

932
        var hash chainhash.Hash
1✔
933
        switch {
1✔
934
        // Return an error if both txid fields are unpopulated.
935
        case len(op.TxidBytes) == 0 && len(op.TxidStr) == 0:
×
936
                return nil, fmt.Errorf("TxidBytes and TxidStr are both " +
×
937
                        "unspecified")
×
938

939
        // The hash was provided as raw bytes.
940
        case len(op.TxidBytes) != 0:
1✔
941
                copy(hash[:], op.TxidBytes)
1✔
942

943
        // The hash was provided as a hex-encoded string.
944
        case len(op.TxidStr) != 0:
1✔
945
                h, err := chainhash.NewHashFromStr(op.TxidStr)
1✔
946
                if err != nil {
1✔
947
                        return nil, err
×
948
                }
×
949
                hash = *h
1✔
950
        }
951

952
        return &wire.OutPoint{
1✔
953
                Hash:  hash,
1✔
954
                Index: op.OutputIndex,
1✔
955
        }, nil
1✔
956
}
957

958
// validateBumpFeeRequest makes sure the deprecated fields are not used when
959
// the new fields are set.
960
func validateBumpFeeRequest(in *BumpFeeRequest, estimator chainfee.Estimator) (
961
        fn.Option[chainfee.SatPerKWeight], bool, error) {
1✔
962

1✔
963
        // Get the specified fee rate if set.
1✔
964
        satPerKwOpt := fn.None[chainfee.SatPerKWeight]()
1✔
965

1✔
966
        // We only allow using either the deprecated field or the new field.
1✔
967
        switch {
1✔
968
        case in.SatPerByte != 0 && in.SatPerVbyte != 0:
×
969
                return satPerKwOpt, false, fmt.Errorf("either SatPerByte or " +
×
970
                        "SatPerVbyte should be set, but not both")
×
971

972
        case in.SatPerByte != 0:
×
973
                satPerKw := chainfee.SatPerVByte(
×
974
                        in.SatPerByte,
×
975
                ).FeePerKWeight()
×
976
                satPerKwOpt = fn.Some(satPerKw)
×
977

978
        case in.SatPerVbyte != 0:
1✔
979
                satPerKw := chainfee.SatPerVByte(
1✔
980
                        in.SatPerVbyte,
1✔
981
                ).FeePerKWeight()
1✔
982
                satPerKwOpt = fn.Some(satPerKw)
1✔
983
        }
984

985
        // We make sure either the conf target or the exact fee rate is
986
        // specified for the starting fee of the fee function.
987
        if in.TargetConf != 0 && !satPerKwOpt.IsNone() {
1✔
988
                return satPerKwOpt, false,
×
989
                        fmt.Errorf("either TargetConf or SatPerVbyte should " +
×
990
                                "be set, to specify the starting fee rate of " +
×
991
                                "the fee function")
×
992
        }
×
993

994
        // In case the user specified a conf target, we estimate the fee rate
995
        // for the given target using the provided estimator.
996
        if in.TargetConf != 0 {
1✔
UNCOV
997
                startingFeeRate, err := estimator.EstimateFeePerKW(
×
UNCOV
998
                        in.TargetConf,
×
UNCOV
999
                )
×
UNCOV
1000
                if err != nil {
×
1001
                        return satPerKwOpt, false, fmt.Errorf("unable to "+
×
1002
                                "estimate fee rate for target conf %d: %w",
×
1003
                                in.TargetConf, err)
×
1004
                }
×
1005

1006
                // Set the starting fee rate to the estimated fee rate.
UNCOV
1007
                satPerKwOpt = fn.Some(startingFeeRate)
×
1008
        }
1009

1010
        var immediate bool
1✔
1011
        switch {
1✔
1012
        case in.Force && in.Immediate:
×
1013
                return satPerKwOpt, false, fmt.Errorf("either Force or " +
×
1014
                        "Immediate should be set, but not both")
×
1015

1016
        case in.Force:
×
1017
                immediate = in.Force
×
1018

1019
        case in.Immediate:
1✔
1020
                immediate = in.Immediate
1✔
1021
        }
1022

1023
        if in.DeadlineDelta != 0 && in.Budget == 0 {
1✔
1024
                return satPerKwOpt, immediate, fmt.Errorf("budget must be " +
×
1025
                        "set if deadline-delta is set")
×
1026
        }
×
1027

1028
        return satPerKwOpt, immediate, nil
1✔
1029
}
1030

1031
// prepareSweepParams creates the sweep params to be used for the sweeper. It
1032
// returns the new params and a bool indicating whether this is an existing
1033
// input.
1034
func (w *WalletKit) prepareSweepParams(in *BumpFeeRequest,
1035
        op wire.OutPoint, currentHeight int32) (sweep.Params, bool, error) {
1✔
1036

1✔
1037
        // Return an error if the bump fee request is invalid.
1✔
1038
        feeRate, immediate, err := validateBumpFeeRequest(
1✔
1039
                in, w.cfg.FeeEstimator,
1✔
1040
        )
1✔
1041
        if err != nil {
1✔
1042
                return sweep.Params{}, false, err
×
1043
        }
×
1044

1045
        // Get the current pending inputs.
1046
        inputMap, err := w.cfg.Sweeper.PendingInputs()
1✔
1047
        if err != nil {
1✔
1048
                return sweep.Params{}, false, fmt.Errorf("unable to get "+
×
1049
                        "pending inputs: %w", err)
×
1050
        }
×
1051

1052
        // Find the pending input.
1053
        //
1054
        // TODO(yy): act differently based on the state of the input?
1055
        inp, ok := inputMap[op]
1✔
1056

1✔
1057
        if !ok {
2✔
1058
                // NOTE: if this input doesn't exist and the new budget is not
1✔
1059
                // specified, the params would have a zero budget.
1✔
1060
                params := sweep.Params{
1✔
1061
                        Immediate:       immediate,
1✔
1062
                        StartingFeeRate: feeRate,
1✔
1063
                        Budget:          btcutil.Amount(in.Budget),
1✔
1064
                }
1✔
1065

1✔
1066
                if in.DeadlineDelta != 0 {
2✔
1067
                        params.DeadlineHeight = fn.Some(
1✔
1068
                                int32(in.DeadlineDelta) + currentHeight,
1✔
1069
                        )
1✔
1070
                }
1✔
1071

1072
                return params, ok, nil
1✔
1073
        }
1074

1075
        // Find the existing budget used for this input. Note that this value
1076
        // must be greater than zero.
1077
        budget := inp.Params.Budget
1✔
1078

1✔
1079
        // Set the new budget if specified. If a new deadline delta is
1✔
1080
        // specified we also require the budget value which is checked in the
1✔
1081
        // validateBumpFeeRequest function.
1✔
1082
        if in.Budget != 0 {
2✔
1083
                budget = btcutil.Amount(in.Budget)
1✔
1084
        }
1✔
1085

1086
        // For an existing input, we assign it first, then overwrite it if
1087
        // a deadline is requested.
1088
        deadline := inp.Params.DeadlineHeight
1✔
1089

1✔
1090
        // Set the deadline if it was specified.
1✔
1091
        //
1✔
1092
        // TODO(yy): upgrade `falafel` so we can make this field optional. Atm
1✔
1093
        // we cannot distinguish between user's not setting the field and
1✔
1094
        // setting it to 0.
1✔
1095
        if in.DeadlineDelta != 0 {
2✔
1096
                deadline = fn.Some(int32(in.DeadlineDelta) + currentHeight)
1✔
1097
        }
1✔
1098

1099
        startingFeeRate := inp.Params.StartingFeeRate
1✔
1100

1✔
1101
        // We only set the starting fee rate if it was specified else we keep
1✔
1102
        // the existing one.
1✔
1103
        if feeRate.IsSome() {
2✔
1104
                startingFeeRate = feeRate
1✔
1105
        }
1✔
1106

1107
        // Prepare the new sweep params.
1108
        //
1109
        // NOTE: if this input doesn't exist and the new budget is not
1110
        // specified, the params would have a zero budget.
1111
        params := sweep.Params{
1✔
1112
                Immediate:       immediate,
1✔
1113
                DeadlineHeight:  deadline,
1✔
1114
                StartingFeeRate: startingFeeRate,
1✔
1115
                Budget:          budget,
1✔
1116
        }
1✔
1117

1✔
1118
        log.Infof("[BumpFee]: bumping fee for existing input=%v, old "+
1✔
1119
                "params=%v, new params=%v", op, inp.Params, params)
1✔
1120

1✔
1121
        return params, ok, nil
1✔
1122
}
1123

1124
// BumpFee allows bumping the fee rate of an arbitrary input. A fee preference
1125
// can be expressed either as a specific fee rate or a delta of blocks in which
1126
// the output should be swept on-chain within. If a fee preference is not
1127
// explicitly specified, then an error is returned. The status of the input
1128
// sweep can be checked through the PendingSweeps RPC.
1129
func (w *WalletKit) BumpFee(ctx context.Context,
1130
        in *BumpFeeRequest) (*BumpFeeResponse, error) {
1✔
1131

1✔
1132
        // Parse the outpoint from the request.
1✔
1133
        op, err := UnmarshallOutPoint(in.Outpoint)
1✔
1134
        if err != nil {
1✔
1135
                return nil, err
×
1136
        }
×
1137

1138
        // Get the current height so we can calculate the deadline height.
1139
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
1✔
1140
        if err != nil {
1✔
1141
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
1142
                        err)
×
1143
        }
×
1144

1145
        // We now create a new sweeping params and update it in the sweeper.
1146
        // This will complicate the RBF conditions if this input has already
1147
        // been offered to sweeper before and it has already been included in a
1148
        // tx with other inputs. If this is the case, two results are possible:
1149
        // - either this input successfully RBFed the existing tx, or,
1150
        // - the budget of this input was not enough to RBF the existing tx.
1151
        params, existing, err := w.prepareSweepParams(in, *op, currentHeight)
1✔
1152
        if err != nil {
1✔
1153
                return nil, err
×
1154
        }
×
1155

1156
        // If this input exists, we will update its params.
1157
        if existing {
2✔
1158
                _, err = w.cfg.Sweeper.UpdateParams(*op, params)
1✔
1159
                if err != nil {
1✔
1160
                        return nil, err
×
1161
                }
×
1162

1163
                return &BumpFeeResponse{
1✔
1164
                        Status: "Successfully registered rbf-tx with sweeper",
1✔
1165
                }, nil
1✔
1166
        }
1167

1168
        // Otherwise, create a new sweeping request for this input.
1169
        err = w.sweepNewInput(op, uint32(currentHeight), params)
1✔
1170
        if err != nil {
2✔
1171
                return nil, err
1✔
1172
        }
1✔
1173

1174
        return &BumpFeeResponse{
1✔
1175
                Status: "Successfully registered CPFP-tx with the sweeper",
1✔
1176
        }, nil
1✔
1177
}
1178

1179
// getWaitingCloseChannel returns the waiting close channel in case it does
1180
// exist in the underlying channel state database.
1181
func (w *WalletKit) getWaitingCloseChannel(
UNCOV
1182
        chanPoint wire.OutPoint) (*channeldb.OpenChannel, error) {
×
UNCOV
1183

×
UNCOV
1184
        // Fetch all channels, which still have their commitment transaction not
×
UNCOV
1185
        // confirmed (waiting close channels).
×
UNCOV
1186
        chans, err := w.cfg.ChanStateDB.FetchWaitingCloseChannels()
×
UNCOV
1187
        if err != nil {
×
1188
                return nil, err
×
1189
        }
×
1190

UNCOV
1191
        channel := fn.Find(chans, func(c *channeldb.OpenChannel) bool {
×
UNCOV
1192
                return c.FundingOutpoint == chanPoint
×
UNCOV
1193
        })
×
1194

UNCOV
1195
        return channel.UnwrapOrErr(errors.New("channel not found"))
×
1196
}
1197

1198
// BumpForceCloseFee bumps the fee rate of an unconfirmed anchor channel. It
1199
// updates the new fee rate parameters with the sweeper subsystem. Additionally
1200
// it will try to create anchor cpfp transactions for all possible commitment
1201
// transactions (local, remote, remote-dangling) so depending on which
1202
// commitment is in the local mempool only one of them will succeed in being
1203
// broadcasted.
1204
func (w *WalletKit) BumpForceCloseFee(_ context.Context,
UNCOV
1205
        in *BumpForceCloseFeeRequest) (*BumpForceCloseFeeResponse, error) {
×
UNCOV
1206

×
UNCOV
1207
        if in.ChanPoint == nil {
×
1208
                return nil, fmt.Errorf("no chan_point provided")
×
1209
        }
×
1210

UNCOV
1211
        lnrpcOutpoint, err := lnrpc.GetChannelOutPoint(in.ChanPoint)
×
UNCOV
1212
        if err != nil {
×
1213
                return nil, err
×
1214
        }
×
1215

UNCOV
1216
        outPoint, err := UnmarshallOutPoint(lnrpcOutpoint)
×
UNCOV
1217
        if err != nil {
×
1218
                return nil, err
×
1219
        }
×
1220

1221
        // Get the relevant channel if it is in the waiting close state.
UNCOV
1222
        channel, err := w.getWaitingCloseChannel(*outPoint)
×
UNCOV
1223
        if err != nil {
×
1224
                return nil, err
×
1225
        }
×
1226

UNCOV
1227
        if !channel.ChanType.HasAnchors() {
×
1228
                return nil, fmt.Errorf("not able to bump the fee of a " +
×
1229
                        "non-anchor channel")
×
1230
        }
×
1231

1232
        // Match pending sweeps with commitments of the channel for which a bump
1233
        // is requested. Depending on the commitment state when force closing
1234
        // the channel we might have up to 3 commitments to consider when
1235
        // bumping the fee.
UNCOV
1236
        commitSet := fn.NewSet[chainhash.Hash]()
×
UNCOV
1237

×
UNCOV
1238
        if channel.LocalCommitment.CommitTx != nil {
×
UNCOV
1239
                localTxID := channel.LocalCommitment.CommitTx.TxHash()
×
UNCOV
1240
                commitSet.Add(localTxID)
×
UNCOV
1241
        }
×
1242

UNCOV
1243
        if channel.RemoteCommitment.CommitTx != nil {
×
UNCOV
1244
                remoteTxID := channel.RemoteCommitment.CommitTx.TxHash()
×
UNCOV
1245
                commitSet.Add(remoteTxID)
×
UNCOV
1246
        }
×
1247

1248
        // Check whether there was a dangling commitment at the time the channel
1249
        // was force closed.
UNCOV
1250
        remoteCommitDiff, err := channel.RemoteCommitChainTip()
×
UNCOV
1251
        if err != nil && !errors.Is(err, channeldb.ErrNoPendingCommit) {
×
1252
                return nil, err
×
1253
        }
×
1254

UNCOV
1255
        if remoteCommitDiff != nil {
×
1256
                hash := remoteCommitDiff.Commitment.CommitTx.TxHash()
×
1257
                commitSet.Add(hash)
×
1258
        }
×
1259

1260
        // Retrieve all of the outputs the UtxoSweeper is currently trying to
1261
        // sweep.
UNCOV
1262
        inputsMap, err := w.cfg.Sweeper.PendingInputs()
×
UNCOV
1263
        if err != nil {
×
1264
                return nil, err
×
1265
        }
×
1266

1267
        // Get the current height so we can calculate the deadline height.
UNCOV
1268
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
×
UNCOV
1269
        if err != nil {
×
1270
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
1271
                        err)
×
1272
        }
×
1273

UNCOV
1274
        pendingSweeps := slices.Collect(maps.Values(inputsMap))
×
UNCOV
1275

×
UNCOV
1276
        // Discard everything except for the anchor sweeps.
×
UNCOV
1277
        anchors := fn.Filter(
×
UNCOV
1278
                pendingSweeps,
×
UNCOV
1279
                func(sweep *sweep.PendingInputResponse) bool {
×
UNCOV
1280
                        // Only filter for anchor inputs because these are the
×
UNCOV
1281
                        // only inputs which can be used to bump a closed
×
UNCOV
1282
                        // unconfirmed commitment transaction.
×
UNCOV
1283
                        isCommitAnchor := sweep.WitnessType ==
×
UNCOV
1284
                                input.CommitmentAnchor
×
UNCOV
1285
                        isTaprootSweepSpend := sweep.WitnessType ==
×
UNCOV
1286
                                input.TaprootAnchorSweepSpend
×
UNCOV
1287
                        if !isCommitAnchor && !isTaprootSweepSpend {
×
1288
                                return false
×
1289
                        }
×
1290

UNCOV
1291
                        return commitSet.Contains(sweep.OutPoint.Hash)
×
1292
                },
1293
        )
1294

UNCOV
1295
        if len(anchors) == 0 {
×
1296
                return nil, fmt.Errorf("unable to find pending anchor outputs")
×
1297
        }
×
1298

1299
        // Filter all relevant anchor sweeps and update the sweep request.
UNCOV
1300
        for _, anchor := range anchors {
×
UNCOV
1301
                // Anchor cpfp bump request are predictable because they are
×
UNCOV
1302
                // swept separately hence not batched with other sweeps (they
×
UNCOV
1303
                // are marked with the exclusive group flag). Bumping the fee
×
UNCOV
1304
                // rate does not create any conflicting fee bump conditions.
×
UNCOV
1305
                // Either the rbf requirements are met or the bump is rejected
×
UNCOV
1306
                // by the mempool rules.
×
UNCOV
1307
                params, existing, err := w.prepareSweepParams(
×
UNCOV
1308
                        &BumpFeeRequest{
×
UNCOV
1309
                                Outpoint:      lnrpcOutpoint,
×
UNCOV
1310
                                TargetConf:    in.TargetConf,
×
UNCOV
1311
                                SatPerVbyte:   in.StartingFeerate,
×
UNCOV
1312
                                Immediate:     in.Immediate,
×
UNCOV
1313
                                Budget:        in.Budget,
×
UNCOV
1314
                                DeadlineDelta: in.DeadlineDelta,
×
UNCOV
1315
                        }, anchor.OutPoint, currentHeight,
×
UNCOV
1316
                )
×
UNCOV
1317
                if err != nil {
×
1318
                        return nil, err
×
1319
                }
×
1320

1321
                // There might be the case when an anchor sweep is confirmed
1322
                // between fetching the pending sweeps and preparing the sweep
1323
                // params. We log this case and proceed.
UNCOV
1324
                if !existing {
×
1325
                        log.Errorf("Sweep anchor input(%v) not known to the " +
×
1326
                                "sweeper subsystem")
×
1327
                        continue
×
1328
                }
1329

UNCOV
1330
                _, err = w.cfg.Sweeper.UpdateParams(anchor.OutPoint, params)
×
UNCOV
1331
                if err != nil {
×
1332
                        return nil, err
×
1333
                }
×
1334
        }
1335

UNCOV
1336
        return &BumpForceCloseFeeResponse{
×
UNCOV
1337
                Status: "Successfully registered anchor-cpfp transaction to" +
×
UNCOV
1338
                        "bump channel force close transaction",
×
UNCOV
1339
        }, nil
×
1340
}
1341

1342
// sweepNewInput handles the case where an input is seen the first time by the
1343
// sweeper. It will fetch the output from the wallet and construct an input and
1344
// offer it to the sweeper.
1345
//
1346
// NOTE: if the budget is not set, the default budget ratio is used.
1347
func (w *WalletKit) sweepNewInput(op *wire.OutPoint, currentHeight uint32,
1348
        params sweep.Params) error {
1✔
1349

1✔
1350
        log.Debugf("Attempting to sweep outpoint %s", op)
1✔
1351

1✔
1352
        // Since the sweeper is not aware of the input, we'll assume the user
1✔
1353
        // is attempting to bump an unconfirmed transaction's fee rate by
1✔
1354
        // sweeping an output within it under control of the wallet with a
1✔
1355
        // higher fee rate. In this case, this will be a CPFP.
1✔
1356
        //
1✔
1357
        // We'll gather all of the information required by the UtxoSweeper in
1✔
1358
        // order to sweep the output.
1✔
1359
        utxo, err := w.cfg.Wallet.FetchOutpointInfo(op)
1✔
1360
        if err != nil {
2✔
1361
                return err
1✔
1362
        }
1✔
1363

1364
        // We're only able to bump the fee of unconfirmed transactions.
1365
        if utxo.Confirmations > 0 {
1✔
1366
                return errors.New("unable to bump fee of a confirmed " +
×
1367
                        "transaction")
×
1368
        }
×
1369

1370
        // TODO(ziggie): The budget value should ideally only be set for CPFP
1371
        // requests because for RBF requests we should have already registered
1372
        // the input including the budget value in the first place. However it
1373
        // might not be set and then depending on the deadline delta fee
1374
        // estimations might become too aggressive. So need to evaluate whether
1375
        // we set a default value here, make it configurable or fail request
1376
        // in that case.
1377
        if params.Budget == 0 {
2✔
1378
                params.Budget = utxo.Value.MulF64(
1✔
1379
                        contractcourt.DefaultBudgetRatio,
1✔
1380
                )
1✔
1381

1✔
1382
                log.Warnf("[BumpFee]: setting default budget value of %v for "+
1✔
1383
                        "input=%v, which will be used for the maximum fee "+
1✔
1384
                        "rate estimation (budget was not specified)",
1✔
1385
                        params.Budget, op)
1✔
1386
        }
1✔
1387

1388
        signDesc := &input.SignDescriptor{
1✔
1389
                Output: &wire.TxOut{
1✔
1390
                        PkScript: utxo.PkScript,
1✔
1391
                        Value:    int64(utxo.Value),
1✔
1392
                },
1✔
1393
                HashType: txscript.SigHashAll,
1✔
1394
        }
1✔
1395

1✔
1396
        var witnessType input.WitnessType
1✔
1397
        switch utxo.AddressType {
1✔
1398
        case lnwallet.WitnessPubKey:
×
1399
                witnessType = input.WitnessKeyHash
×
1400
        case lnwallet.NestedWitnessPubKey:
×
1401
                witnessType = input.NestedWitnessKeyHash
×
1402
        case lnwallet.TaprootPubkey:
1✔
1403
                witnessType = input.TaprootPubKeySpend
1✔
1404
                signDesc.HashType = txscript.SigHashDefault
1✔
1405
        default:
×
1406
                return fmt.Errorf("unknown input witness %v", op)
×
1407
        }
1408

1409
        log.Infof("[BumpFee]: bumping fee for new input=%v, params=%v", op,
1✔
1410
                params)
1✔
1411

1✔
1412
        inp := input.NewBaseInput(op, witnessType, signDesc, currentHeight)
1✔
1413
        if _, err = w.cfg.Sweeper.SweepInput(inp, params); err != nil {
1✔
1414
                return err
×
1415
        }
×
1416

1417
        return nil
1✔
1418
}
1419

1420
// ListSweeps returns a list of the sweeps that our node has published.
1421
func (w *WalletKit) ListSweeps(ctx context.Context,
1422
        in *ListSweepsRequest) (*ListSweepsResponse, error) {
1✔
1423

1✔
1424
        sweeps, err := w.cfg.Sweeper.ListSweeps()
1✔
1425
        if err != nil {
1✔
1426
                return nil, err
×
1427
        }
×
1428

1429
        sweepTxns := make(map[string]bool)
1✔
1430
        for _, sweep := range sweeps {
2✔
1431
                sweepTxns[sweep.String()] = true
1✔
1432
        }
1✔
1433

1434
        // Some of our sweeps could have been replaced by fee, or dropped out
1435
        // of the mempool. Here, we lookup our wallet transactions so that we
1436
        // can match our list of sweeps against the list of transactions that
1437
        // the wallet is still tracking. Sweeps are currently always swept to
1438
        // the default wallet account.
1439
        txns, firstIdx, lastIdx, err := w.cfg.Wallet.ListTransactionDetails(
1✔
1440
                in.StartHeight, btcwallet.UnconfirmedHeight,
1✔
1441
                lnwallet.DefaultAccountName, 0, 0,
1✔
1442
        )
1✔
1443
        if err != nil {
1✔
1444
                return nil, err
×
1445
        }
×
1446

1447
        var (
1✔
1448
                txids     []string
1✔
1449
                txDetails []*lnwallet.TransactionDetail
1✔
1450
        )
1✔
1451

1✔
1452
        for _, tx := range txns {
2✔
1453
                _, ok := sweepTxns[tx.Hash.String()]
1✔
1454
                if !ok {
2✔
1455
                        continue
1✔
1456
                }
1457

1458
                // Add the txid or full tx details depending on whether we want
1459
                // verbose output or not.
1460
                if in.Verbose {
2✔
1461
                        txDetails = append(txDetails, tx)
1✔
1462
                } else {
2✔
1463
                        txids = append(txids, tx.Hash.String())
1✔
1464
                }
1✔
1465
        }
1466

1467
        if in.Verbose {
2✔
1468
                return &ListSweepsResponse{
1✔
1469
                        Sweeps: &ListSweepsResponse_TransactionDetails{
1✔
1470
                                TransactionDetails: lnrpc.RPCTransactionDetails(
1✔
1471
                                        txDetails, firstIdx, lastIdx,
1✔
1472
                                ),
1✔
1473
                        },
1✔
1474
                }, nil
1✔
1475
        }
1✔
1476

1477
        return &ListSweepsResponse{
1✔
1478
                Sweeps: &ListSweepsResponse_TransactionIds{
1✔
1479
                        TransactionIds: &ListSweepsResponse_TransactionIDs{
1✔
1480
                                TransactionIds: txids,
1✔
1481
                        },
1✔
1482
                },
1✔
1483
        }, nil
1✔
1484
}
1485

1486
// LabelTransaction adds a label to a transaction.
1487
func (w *WalletKit) LabelTransaction(ctx context.Context,
1488
        req *LabelTransactionRequest) (*LabelTransactionResponse, error) {
1✔
1489

1✔
1490
        // Check that the label provided in non-zero.
1✔
1491
        if len(req.Label) == 0 {
2✔
1492
                return nil, ErrZeroLabel
1✔
1493
        }
1✔
1494

1495
        // Validate the length of the non-zero label. We do not need to use the
1496
        // label returned here, because the original is non-zero so will not
1497
        // be replaced.
1498
        if _, err := labels.ValidateAPI(req.Label); err != nil {
1✔
1499
                return nil, err
×
1500
        }
×
1501

1502
        hash, err := chainhash.NewHash(req.Txid)
1✔
1503
        if err != nil {
1✔
1504
                return nil, err
×
1505
        }
×
1506

1507
        err = w.cfg.Wallet.LabelTransaction(*hash, req.Label, req.Overwrite)
1✔
1508

1✔
1509
        return &LabelTransactionResponse{
1✔
1510
                Status: fmt.Sprintf("transaction label '%s' added", req.Label),
1✔
1511
        }, err
1✔
1512
}
1513

1514
// FundPsbt creates a fully populated PSBT that contains enough inputs to fund
1515
// the outputs specified in the template. There are three ways a user can
1516
// specify what we call the template (a list of inputs and outputs to use in the
1517
// PSBT): Either as a PSBT packet directly with no coin selection (using the
1518
// legacy "psbt" field), a PSBT with advanced coin selection support (using the
1519
// new "coin_select" field) or as a raw RPC message (using the "raw" field).
1520
// The legacy "psbt" and "raw" modes, the following restrictions apply:
1521
//  1. If there are no inputs specified in the template, coin selection is
1522
//     performed automatically.
1523
//  2. If the template does contain any inputs, it is assumed that full coin
1524
//     selection happened externally and no additional inputs are added. If the
1525
//     specified inputs aren't enough to fund the outputs with the given fee
1526
//     rate, an error is returned.
1527
//
1528
// The new "coin_select" mode does not have these restrictions and allows the
1529
// user to specify a PSBT with inputs and outputs and still perform coin
1530
// selection on top of that.
1531
// For all modes this RPC requires any inputs that are specified to be locked by
1532
// the user (if they belong to this node in the first place).
1533
// After either selecting or verifying the inputs, all input UTXOs are locked
1534
// with an internal app ID. A custom address type for change can be specified
1535
// for default accounts and single imported public keys (only P2TR for now).
1536
// Otherwise, P2WPKH will be used by default. No custom address type should be
1537
// provided for custom accounts as we will always generate the change address
1538
// using the coin selection key scope.
1539
//
1540
// NOTE: If this method returns without an error, it is the caller's
1541
// responsibility to either spend the locked UTXOs (by finalizing and then
1542
// publishing the transaction) or to unlock/release the locked UTXOs in case of
1543
// an error on the caller's side.
1544
func (w *WalletKit) FundPsbt(_ context.Context,
1545
        req *FundPsbtRequest) (*FundPsbtResponse, error) {
1✔
1546

1✔
1547
        coinSelectionStrategy, err := lnrpc.UnmarshallCoinSelectionStrategy(
1✔
1548
                req.CoinSelectionStrategy, w.cfg.CoinSelectionStrategy,
1✔
1549
        )
1✔
1550
        if err != nil {
1✔
1551
                return nil, err
×
1552
        }
×
1553

1554
        // Determine the desired transaction fee.
1555
        var feeSatPerKW chainfee.SatPerKWeight
1✔
1556
        switch {
1✔
1557
        // Estimate the fee by the target number of blocks to confirmation.
1558
        case req.GetTargetConf() != 0:
×
1559
                targetConf := req.GetTargetConf()
×
1560
                if targetConf < 2 {
×
1561
                        return nil, fmt.Errorf("confirmation target must be " +
×
1562
                                "greater than 1")
×
1563
                }
×
1564

1565
                feeSatPerKW, err = w.cfg.FeeEstimator.EstimateFeePerKW(
×
1566
                        targetConf,
×
1567
                )
×
1568
                if err != nil {
×
1569
                        return nil, fmt.Errorf("could not estimate fee: %w",
×
1570
                                err)
×
1571
                }
×
1572

1573
        // Convert the fee to sat/kW from the specified sat/vByte.
1574
        case req.GetSatPerVbyte() != 0:
1✔
1575
                feeSatPerKW = chainfee.SatPerKVByte(
1✔
1576
                        req.GetSatPerVbyte() * 1000,
1✔
1577
                ).FeePerKWeight()
1✔
1578

1579
        case req.GetSatPerKw() != 0:
×
1580
                feeSatPerKW = chainfee.SatPerKWeight(req.GetSatPerKw())
×
1581

1582
        default:
×
1583
                return nil, fmt.Errorf("fee definition missing, need to " +
×
1584
                        "specify either target_conf, sat_per_vbyte or " +
×
1585
                        "sat_per_kw")
×
1586
        }
1587

1588
        // Then, we'll extract the minimum number of confirmations that each
1589
        // output we use to fund the transaction should satisfy.
1590
        minConfs, err := lnrpc.ExtractMinConfs(
1✔
1591
                req.GetMinConfs(), req.GetSpendUnconfirmed(),
1✔
1592
        )
1✔
1593
        if err != nil {
1✔
1594
                return nil, err
×
1595
        }
×
1596

1597
        // We'll assume the PSBT will be funded by the default account unless
1598
        // otherwise specified.
1599
        account := lnwallet.DefaultAccountName
1✔
1600
        if req.Account != "" {
2✔
1601
                account = req.Account
1✔
1602
        }
1✔
1603

1604
        var customLockID *wtxmgr.LockID
1✔
1605
        if len(req.CustomLockId) > 0 {
2✔
1606
                lockID := wtxmgr.LockID{}
1✔
1607
                if len(req.CustomLockId) != len(lockID) {
1✔
1608
                        return nil, fmt.Errorf("custom lock ID must be " +
×
1609
                                "exactly 32 bytes")
×
1610
                }
×
1611

1612
                copy(lockID[:], req.CustomLockId)
1✔
1613
                customLockID = &lockID
1✔
1614
        }
1615

1616
        var customLockDuration time.Duration
1✔
1617
        if req.LockExpirationSeconds != 0 {
2✔
1618
                customLockDuration = time.Duration(req.LockExpirationSeconds) *
1✔
1619
                        time.Second
1✔
1620
        }
1✔
1621

1622
        // There are three ways a user can specify what we call the template (a
1623
        // list of inputs and outputs to use in the PSBT): Either as a PSBT
1624
        // packet directly with no coin selection, a PSBT with coin selection or
1625
        // as a special RPC message. Find out which one the user wants to use,
1626
        // they are mutually exclusive.
1627
        switch {
1✔
1628
        // The template is specified as a PSBT. All we have to do is parse it.
1629
        case req.GetPsbt() != nil:
1✔
1630
                r := bytes.NewReader(req.GetPsbt())
1✔
1631
                packet, err := psbt.NewFromRawBytes(r, false)
1✔
1632
                if err != nil {
1✔
1633
                        return nil, fmt.Errorf("could not parse PSBT: %w", err)
×
1634
                }
×
1635

1636
                // Run the actual funding process now, using the internal
1637
                // wallet.
1638
                return w.fundPsbtInternalWallet(
1✔
1639
                        account, keyScopeFromChangeAddressType(req.ChangeType),
1✔
1640
                        packet, minConfs, feeSatPerKW, coinSelectionStrategy,
1✔
1641
                        customLockID, customLockDuration,
1✔
1642
                )
1✔
1643

1644
        // The template is specified as a PSBT with the intention to perform
1645
        // coin selection even if inputs are already present.
1646
        case req.GetCoinSelect() != nil:
1✔
1647
                coinSelectRequest := req.GetCoinSelect()
1✔
1648
                r := bytes.NewReader(coinSelectRequest.Psbt)
1✔
1649
                packet, err := psbt.NewFromRawBytes(r, false)
1✔
1650
                if err != nil {
1✔
1651
                        return nil, fmt.Errorf("could not parse PSBT: %w", err)
×
1652
                }
×
1653

1654
                numOutputs := int32(len(packet.UnsignedTx.TxOut))
1✔
1655
                if numOutputs == 0 {
1✔
1656
                        return nil, fmt.Errorf("no outputs specified in " +
×
1657
                                "template")
×
1658
                }
×
1659

1660
                outputSum := int64(0)
1✔
1661
                for _, txOut := range packet.UnsignedTx.TxOut {
2✔
1662
                        outputSum += txOut.Value
1✔
1663
                }
1✔
1664
                if outputSum <= 0 {
1✔
1665
                        return nil, fmt.Errorf("output sum must be positive")
×
1666
                }
×
1667

1668
                var (
1✔
1669
                        changeIndex int32 = -1
1✔
1670
                        changeType  chanfunding.ChangeAddressType
1✔
1671
                )
1✔
1672
                switch t := coinSelectRequest.ChangeOutput.(type) {
1✔
1673
                // The user wants to use an existing output as change output.
1674
                case *PsbtCoinSelect_ExistingOutputIndex:
1✔
1675
                        if t.ExistingOutputIndex < 0 ||
1✔
1676
                                t.ExistingOutputIndex >= numOutputs {
1✔
1677

×
1678
                                return nil, fmt.Errorf("change output index "+
×
1679
                                        "out of range: %d",
×
1680
                                        t.ExistingOutputIndex)
×
1681
                        }
×
1682

1683
                        changeIndex = t.ExistingOutputIndex
1✔
1684

1✔
1685
                        changeOut := packet.UnsignedTx.TxOut[changeIndex]
1✔
1686
                        _, err := txscript.ParsePkScript(changeOut.PkScript)
1✔
1687
                        if err != nil {
1✔
1688
                                return nil, fmt.Errorf("error parsing change "+
×
1689
                                        "script: %w", err)
×
1690
                        }
×
1691

1692
                        changeType = chanfunding.ExistingChangeAddress
1✔
1693

1694
                // The user wants to use a new output as change output.
1695
                case *PsbtCoinSelect_Add:
×
1696
                        // We already set the change index to -1 above to
×
1697
                        // indicate no change output should be used if possible
×
1698
                        // or a new one should be created if needed. So we only
×
1699
                        // need to parse the type of change output we want to
×
1700
                        // create.
×
1701
                        switch req.ChangeType {
×
1702
                        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
×
1703
                                changeType = chanfunding.P2TRChangeAddress
×
1704

1705
                        default:
×
1706
                                changeType = chanfunding.P2WKHChangeAddress
×
1707
                        }
1708

1709
                default:
×
1710
                        return nil, fmt.Errorf("unknown change output type")
×
1711
                }
1712

1713
                maxFeeRatio := chanfunding.DefaultMaxFeeRatio
1✔
1714

1✔
1715
                if req.MaxFeeRatio != 0 {
1✔
1716
                        maxFeeRatio = req.MaxFeeRatio
×
1717
                }
×
1718

1719
                // Run the actual funding process now, using the channel funding
1720
                // coin selection algorithm.
1721
                return w.fundPsbtCoinSelect(
1✔
1722
                        account, changeIndex, packet, minConfs, changeType,
1✔
1723
                        feeSatPerKW, coinSelectionStrategy, maxFeeRatio,
1✔
1724
                        customLockID, customLockDuration,
1✔
1725
                )
1✔
1726

1727
        // The template is specified as a RPC message. We need to create a new
1728
        // PSBT and copy the RPC information over.
1729
        case req.GetRaw() != nil:
1✔
1730
                tpl := req.GetRaw()
1✔
1731

1✔
1732
                txOut := make([]*wire.TxOut, 0, len(tpl.Outputs))
1✔
1733
                for addrStr, amt := range tpl.Outputs {
2✔
1734
                        addr, err := btcutil.DecodeAddress(
1✔
1735
                                addrStr, w.cfg.ChainParams,
1✔
1736
                        )
1✔
1737
                        if err != nil {
1✔
1738
                                return nil, fmt.Errorf("error parsing address "+
×
1739
                                        "%s for network %s: %v", addrStr,
×
1740
                                        w.cfg.ChainParams.Name, err)
×
1741
                        }
×
1742

1743
                        if !addr.IsForNet(w.cfg.ChainParams) {
1✔
1744
                                return nil, fmt.Errorf("address is not for %s",
×
1745
                                        w.cfg.ChainParams.Name)
×
1746
                        }
×
1747

1748
                        pkScript, err := txscript.PayToAddrScript(addr)
1✔
1749
                        if err != nil {
1✔
1750
                                return nil, fmt.Errorf("error getting pk "+
×
1751
                                        "script for address %s: %w", addrStr,
×
1752
                                        err)
×
1753
                        }
×
1754

1755
                        txOut = append(txOut, &wire.TxOut{
1✔
1756
                                Value:    int64(amt),
1✔
1757
                                PkScript: pkScript,
1✔
1758
                        })
1✔
1759
                }
1760

1761
                txIn := make([]*wire.OutPoint, len(tpl.Inputs))
1✔
1762
                for idx, in := range tpl.Inputs {
1✔
1763
                        op, err := UnmarshallOutPoint(in)
×
1764
                        if err != nil {
×
1765
                                return nil, fmt.Errorf("error parsing "+
×
1766
                                        "outpoint: %w", err)
×
1767
                        }
×
1768
                        txIn[idx] = op
×
1769
                }
1770

1771
                sequences := make([]uint32, len(txIn))
1✔
1772
                packet, err := psbt.New(txIn, txOut, 2, 0, sequences)
1✔
1773
                if err != nil {
1✔
1774
                        return nil, fmt.Errorf("could not create PSBT: %w", err)
×
1775
                }
×
1776

1777
                // Run the actual funding process now, using the internal
1778
                // wallet.
1779
                return w.fundPsbtInternalWallet(
1✔
1780
                        account, keyScopeFromChangeAddressType(req.ChangeType),
1✔
1781
                        packet, minConfs, feeSatPerKW, coinSelectionStrategy,
1✔
1782
                        customLockID, customLockDuration,
1✔
1783
                )
1✔
1784

1785
        default:
×
1786
                return nil, fmt.Errorf("transaction template missing, need " +
×
1787
                        "to specify either PSBT or raw TX template")
×
1788
        }
1789
}
1790

1791
// fundPsbtInternalWallet uses the "old" PSBT funding method of the internal
1792
// wallet that does not allow specifying custom inputs while selecting coins.
1793
func (w *WalletKit) fundPsbtInternalWallet(account string,
1794
        keyScope *waddrmgr.KeyScope, packet *psbt.Packet, minConfs int32,
1795
        feeSatPerKW chainfee.SatPerKWeight, strategy base.CoinSelectionStrategy,
1796
        customLockID *wtxmgr.LockID, customLockDuration time.Duration) (
1797
        *FundPsbtResponse, error) {
1✔
1798

1✔
1799
        // The RPC parsing part is now over. Several of the following operations
1✔
1800
        // require us to hold the global coin selection lock, so we do the rest
1✔
1801
        // of the tasks while holding the lock. The result is a list of locked
1✔
1802
        // UTXOs.
1✔
1803
        var response *FundPsbtResponse
1✔
1804
        err := w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
2✔
1805
                // In case the user did specify inputs, we need to make sure
1✔
1806
                // they are known to us, still unspent and not yet locked.
1✔
1807
                if len(packet.UnsignedTx.TxIn) > 0 {
2✔
1808
                        // Get a list of all unspent witness outputs.
1✔
1809
                        utxos, err := w.cfg.Wallet.ListUnspentWitness(
1✔
1810
                                minConfs, defaultMaxConf, account,
1✔
1811
                        )
1✔
1812
                        if err != nil {
1✔
1813
                                return err
×
1814
                        }
×
1815

1816
                        // filterFn makes sure utxos which are unconfirmed and
1817
                        // still used by the sweeper are not used.
1818
                        filterFn := func(u *lnwallet.Utxo) bool {
2✔
1819
                                // Confirmed utxos are always allowed.
1✔
1820
                                if u.Confirmations > 0 {
2✔
1821
                                        return true
1✔
1822
                                }
1✔
1823

1824
                                // Unconfirmed utxos in use by the sweeper are
1825
                                // not stable to use because they can be
1826
                                // replaced.
1827
                                if w.cfg.Sweeper.IsSweeperOutpoint(u.OutPoint) {
2✔
1828
                                        log.Warnf("Cannot use unconfirmed "+
1✔
1829
                                                "utxo=%v because it is "+
1✔
1830
                                                "unstable and could be "+
1✔
1831
                                                "replaced", u.OutPoint)
1✔
1832

1✔
1833
                                        return false
1✔
1834
                                }
1✔
1835

1836
                                return true
×
1837
                        }
1838

1839
                        eligibleUtxos := fn.Filter(utxos, filterFn)
1✔
1840

1✔
1841
                        // Validate all inputs against our known list of UTXOs
1✔
1842
                        // now.
1✔
1843
                        err = verifyInputsUnspent(
1✔
1844
                                packet.UnsignedTx.TxIn, eligibleUtxos,
1✔
1845
                        )
1✔
1846
                        if err != nil {
2✔
1847
                                return err
1✔
1848
                        }
1✔
1849
                }
1850

1851
                // currentHeight is needed to determine whether the internal
1852
                // wallet utxo is still unconfirmed.
1853
                _, currentHeight, err := w.cfg.Chain.GetBestBlock()
1✔
1854
                if err != nil {
1✔
1855
                        return fmt.Errorf("unable to retrieve current "+
×
1856
                                "height: %v", err)
×
1857
                }
×
1858

1859
                // restrictUnstableUtxos is a filter function which disallows
1860
                // the usage of unconfirmed outputs published (still in use) by
1861
                // the sweeper.
1862
                restrictUnstableUtxos := func(utxo wtxmgr.Credit) bool {
2✔
1863
                        // Wallet utxos which are unmined have a height
1✔
1864
                        // of -1.
1✔
1865
                        if utxo.Height != -1 && utxo.Height <= currentHeight {
2✔
1866
                                // Confirmed utxos are always allowed.
1✔
1867
                                return true
1✔
1868
                        }
1✔
1869

1870
                        // Utxos used by the sweeper are not used for
1871
                        // channel openings.
1872
                        allowed := !w.cfg.Sweeper.IsSweeperOutpoint(
1✔
1873
                                utxo.OutPoint,
1✔
1874
                        )
1✔
1875
                        if !allowed {
2✔
1876
                                log.Warnf("Cannot use unconfirmed "+
1✔
1877
                                        "utxo=%v because it is "+
1✔
1878
                                        "unstable and could be "+
1✔
1879
                                        "replaced", utxo.OutPoint)
1✔
1880
                        }
1✔
1881

1882
                        return allowed
1✔
1883
                }
1884

1885
                // We made sure the input from the user is as sane as possible.
1886
                // We can now ask the wallet to fund the TX. This will not yet
1887
                // lock any coins but might still change the wallet DB by
1888
                // generating a new change address.
1889
                changeIndex, err := w.cfg.Wallet.FundPsbt(
1✔
1890
                        packet, minConfs, feeSatPerKW, account, keyScope,
1✔
1891
                        strategy, restrictUnstableUtxos,
1✔
1892
                )
1✔
1893
                if err != nil {
2✔
1894
                        return fmt.Errorf("wallet couldn't fund PSBT: %w", err)
1✔
1895
                }
1✔
1896

1897
                // Now we have obtained a set of coins that can be used to fund
1898
                // the TX. Let's lock them to be sure they aren't spent by the
1899
                // time the PSBT is published. This is the action we do here
1900
                // that could cause an error. Therefore, if some of the UTXOs
1901
                // cannot be locked, the rollback of the other's locks also
1902
                // happens in this function. If we ever need to do more after
1903
                // this function, we need to extract the rollback needs to be
1904
                // extracted into a defer.
1905
                outpoints := make([]wire.OutPoint, len(packet.UnsignedTx.TxIn))
1✔
1906
                for i, txIn := range packet.UnsignedTx.TxIn {
2✔
1907
                        outpoints[i] = txIn.PreviousOutPoint
1✔
1908
                }
1✔
1909

1910
                response, err = w.lockAndCreateFundingResponse(
1✔
1911
                        packet, outpoints, changeIndex, customLockID,
1✔
1912
                        customLockDuration,
1✔
1913
                )
1✔
1914

1✔
1915
                return err
1✔
1916
        })
1917
        if err != nil {
2✔
1918
                return nil, err
1✔
1919
        }
1✔
1920

1921
        return response, nil
1✔
1922
}
1923

1924
// fundPsbtCoinSelect uses the "new" PSBT funding method using the channel
1925
// funding coin selection algorithm that allows specifying custom inputs while
1926
// selecting coins.
1927
func (w *WalletKit) fundPsbtCoinSelect(account string, changeIndex int32,
1928
        packet *psbt.Packet, minConfs int32,
1929
        changeType chanfunding.ChangeAddressType,
1930
        feeRate chainfee.SatPerKWeight, strategy base.CoinSelectionStrategy,
1931
        maxFeeRatio float64, customLockID *wtxmgr.LockID,
1932
        customLockDuration time.Duration) (*FundPsbtResponse, error) {
1✔
1933

1✔
1934
        // We want to make sure we don't select any inputs that are already
1✔
1935
        // specified in the template. To do that, we require those inputs to
1✔
1936
        // either not belong to this lnd at all or to be already locked through
1✔
1937
        // a manual lock call by the user. Either way, they should not appear in
1✔
1938
        // the list of unspent outputs.
1✔
1939
        err := w.assertNotAvailable(packet.UnsignedTx.TxIn, minConfs, account)
1✔
1940
        if err != nil {
1✔
1941
                return nil, err
×
1942
        }
×
1943

1944
        // In case the user just specified the input outpoints of UTXOs we own,
1945
        // the fee estimation below will error out because the UTXO information
1946
        // is missing. We need to fetch the UTXO information from the wallet
1947
        // and add it to the PSBT. We ignore inputs we don't actually know as
1948
        // they could belong to another wallet.
1949
        err = w.cfg.Wallet.DecorateInputs(packet, false)
1✔
1950
        if err != nil {
1✔
1951
                return nil, fmt.Errorf("error decorating inputs: %w", err)
×
1952
        }
×
1953

1954
        // Before we select anything, we need to calculate the input, output and
1955
        // current weight amounts. While doing that we also ensure the PSBT has
1956
        // all the required information we require at this step.
1957
        var (
1✔
1958
                inputSum, outputSum btcutil.Amount
1✔
1959
                estimator           input.TxWeightEstimator
1✔
1960
        )
1✔
1961
        for i := range packet.Inputs {
2✔
1962
                in := packet.Inputs[i]
1✔
1963

1✔
1964
                err := btcwallet.EstimateInputWeight(&in, &estimator)
1✔
1965
                if err != nil {
1✔
1966
                        return nil, fmt.Errorf("error estimating input "+
×
1967
                                "weight: %w", err)
×
1968
                }
×
1969

1970
                inputSum += btcutil.Amount(in.WitnessUtxo.Value)
1✔
1971
        }
1972
        for i := range packet.UnsignedTx.TxOut {
2✔
1973
                out := packet.UnsignedTx.TxOut[i]
1✔
1974

1✔
1975
                estimator.AddOutput(out.PkScript)
1✔
1976
                outputSum += btcutil.Amount(out.Value)
1✔
1977
        }
1✔
1978

1979
        // The amount we want to fund is the total output sum plus the current
1980
        // fee estimate, minus the sum of any already specified inputs. Since we
1981
        // pass the estimator of the current transaction into the coin selection
1982
        // algorithm, we don't need to subtract the fees here.
1983
        fundingAmount := outputSum - inputSum
1✔
1984

1✔
1985
        var changeDustLimit btcutil.Amount
1✔
1986
        switch changeType {
1✔
1987
        case chanfunding.P2TRChangeAddress:
×
1988
                changeDustLimit = lnwallet.DustLimitForSize(input.P2TRSize)
×
1989

1990
        case chanfunding.P2WKHChangeAddress:
×
1991
                changeDustLimit = lnwallet.DustLimitForSize(input.P2WPKHSize)
×
1992

1993
        case chanfunding.ExistingChangeAddress:
1✔
1994
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
1✔
1995
                changeDustLimit = lnwallet.DustLimitForSize(
1✔
1996
                        len(changeOut.PkScript),
1✔
1997
                )
1✔
1998
        }
1999

2000
        // Do we already have enough inputs specified to pay for the TX as it
2001
        // is? In that case we only need to allocate any change, if there is
2002
        // any.
2003
        packetFeeNoChange := feeRate.FeeForWeight(estimator.Weight())
1✔
2004
        if inputSum >= outputSum+packetFeeNoChange {
1✔
2005
                // Calculate the packet's fee with a change output so, so we can
×
2006
                // let the coin selection algorithm decide whether to use a
×
2007
                // change output or not.
×
2008
                switch changeType {
×
2009
                case chanfunding.P2TRChangeAddress:
×
2010
                        estimator.AddP2TROutput()
×
2011

2012
                case chanfunding.P2WKHChangeAddress:
×
2013
                        estimator.AddP2WKHOutput()
×
2014
                }
2015
                packetFeeWithChange := feeRate.FeeForWeight(estimator.Weight())
×
2016

×
2017
                changeAmt, needMore, err := chanfunding.CalculateChangeAmount(
×
2018
                        inputSum, outputSum, packetFeeNoChange,
×
2019
                        packetFeeWithChange, changeDustLimit, changeType,
×
2020
                        maxFeeRatio,
×
2021
                )
×
2022
                if err != nil {
×
2023
                        return nil, fmt.Errorf("error calculating change "+
×
2024
                                "amount: %w", err)
×
2025
                }
×
2026

2027
                // We shouldn't get into this branch if the input sum isn't
2028
                // enough to pay for the current package without a change
2029
                // output. So this should never be non-zero.
2030
                if needMore != 0 {
×
2031
                        return nil, fmt.Errorf("internal error with change " +
×
2032
                                "amount calculation")
×
2033
                }
×
2034

2035
                if changeAmt > 0 {
×
2036
                        changeIndex, err = w.handleChange(
×
2037
                                packet, changeIndex, int64(changeAmt),
×
2038
                                changeType, account,
×
2039
                        )
×
2040
                        if err != nil {
×
2041
                                return nil, fmt.Errorf("error handling change "+
×
2042
                                        "amount: %w", err)
×
2043
                        }
×
2044
                }
2045

2046
                // We're done. Let's serialize and return the updated package.
2047
                return w.lockAndCreateFundingResponse(
×
2048
                        packet, nil, changeIndex, customLockID,
×
2049
                        customLockDuration,
×
2050
                )
×
2051
        }
2052

2053
        // The RPC parsing part is now over. Several of the following operations
2054
        // require us to hold the global coin selection lock, so we do the rest
2055
        // of the tasks while holding the lock. The result is a list of locked
2056
        // UTXOs.
2057
        var response *FundPsbtResponse
1✔
2058
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
2✔
2059
                // Get a list of all unspent witness outputs.
1✔
2060
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
1✔
2061
                        minConfs, defaultMaxConf, account,
1✔
2062
                )
1✔
2063
                if err != nil {
1✔
2064
                        return err
×
2065
                }
×
2066

2067
                coins := make([]base.Coin, len(utxos))
1✔
2068
                for i, utxo := range utxos {
2✔
2069
                        coins[i] = base.Coin{
1✔
2070
                                TxOut: wire.TxOut{
1✔
2071
                                        Value:    int64(utxo.Value),
1✔
2072
                                        PkScript: utxo.PkScript,
1✔
2073
                                },
1✔
2074
                                OutPoint: utxo.OutPoint,
1✔
2075
                        }
1✔
2076
                }
1✔
2077

2078
                selectedCoins, changeAmount, err := chanfunding.CoinSelect(
1✔
2079
                        feeRate, fundingAmount, changeDustLimit, coins,
1✔
2080
                        strategy, estimator, changeType, maxFeeRatio,
1✔
2081
                )
1✔
2082
                if err != nil {
1✔
2083
                        return fmt.Errorf("error selecting coins: %w", err)
×
2084
                }
×
2085

2086
                if changeAmount > 0 {
2✔
2087
                        changeIndex, err = w.handleChange(
1✔
2088
                                packet, changeIndex, int64(changeAmount),
1✔
2089
                                changeType, account,
1✔
2090
                        )
1✔
2091
                        if err != nil {
1✔
2092
                                return fmt.Errorf("error handling change "+
×
2093
                                        "amount: %w", err)
×
2094
                        }
×
2095
                }
2096

2097
                addedOutpoints := make([]wire.OutPoint, len(selectedCoins))
1✔
2098
                for i := range selectedCoins {
2✔
2099
                        coin := selectedCoins[i]
1✔
2100
                        addedOutpoints[i] = coin.OutPoint
1✔
2101

1✔
2102
                        packet.UnsignedTx.TxIn = append(
1✔
2103
                                packet.UnsignedTx.TxIn, &wire.TxIn{
1✔
2104
                                        PreviousOutPoint: coin.OutPoint,
1✔
2105
                                },
1✔
2106
                        )
1✔
2107
                        packet.Inputs = append(packet.Inputs, psbt.PInput{
1✔
2108
                                WitnessUtxo: &coin.TxOut,
1✔
2109
                        })
1✔
2110
                }
1✔
2111

2112
                // Now that we've added the bare TX inputs, we also need to add
2113
                // the more verbose input information to the packet, so a future
2114
                // signer doesn't need to do any lookups. We skip any inputs
2115
                // that our wallet doesn't own.
2116
                err = w.cfg.Wallet.DecorateInputs(packet, false)
1✔
2117
                if err != nil {
1✔
2118
                        return fmt.Errorf("error decorating inputs: %w", err)
×
2119
                }
×
2120

2121
                response, err = w.lockAndCreateFundingResponse(
1✔
2122
                        packet, addedOutpoints, changeIndex, customLockID,
1✔
2123
                        customLockDuration,
1✔
2124
                )
1✔
2125

1✔
2126
                return err
1✔
2127
        })
2128
        if err != nil {
1✔
2129
                return nil, err
×
2130
        }
×
2131

2132
        return response, nil
1✔
2133
}
2134

2135
// assertNotAvailable makes sure the specified inputs either don't belong to
2136
// this node or are already locked by the user.
2137
func (w *WalletKit) assertNotAvailable(inputs []*wire.TxIn, minConfs int32,
2138
        account string) error {
1✔
2139

1✔
2140
        return w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
2✔
2141
                // Get a list of all unspent witness outputs.
1✔
2142
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
1✔
2143
                        minConfs, defaultMaxConf, account,
1✔
2144
                )
1✔
2145
                if err != nil {
1✔
2146
                        return fmt.Errorf("error fetching UTXOs: %w", err)
×
2147
                }
×
2148

2149
                // We'll now check that none of the inputs specified in the
2150
                // template are available to us. That means they either don't
2151
                // belong to us or are already locked by the user.
2152
                for _, txIn := range inputs {
2✔
2153
                        for _, utxo := range utxos {
2✔
2154
                                if txIn.PreviousOutPoint == utxo.OutPoint {
1✔
2155
                                        return fmt.Errorf("input %v is not "+
×
2156
                                                "locked", txIn.PreviousOutPoint)
×
2157
                                }
×
2158
                        }
2159
                }
2160

2161
                return nil
1✔
2162
        })
2163
}
2164

2165
// lockAndCreateFundingResponse locks the given outpoints and creates a funding
2166
// response with the serialized PSBT, the change index and the locked UTXOs.
2167
func (w *WalletKit) lockAndCreateFundingResponse(packet *psbt.Packet,
2168
        newOutpoints []wire.OutPoint, changeIndex int32,
2169
        customLockID *wtxmgr.LockID, customLockDuration time.Duration) (
2170
        *FundPsbtResponse, error) {
1✔
2171

1✔
2172
        // Make sure we can properly serialize the packet. If this goes wrong
1✔
2173
        // then something isn't right with the inputs, and we probably shouldn't
1✔
2174
        // try to lock any of them.
1✔
2175
        var buf bytes.Buffer
1✔
2176
        err := packet.Serialize(&buf)
1✔
2177
        if err != nil {
1✔
2178
                return nil, fmt.Errorf("error serializing funded PSBT: %w", err)
×
2179
        }
×
2180

2181
        locks, err := lockInputs(
1✔
2182
                w.cfg.Wallet, newOutpoints, customLockID, customLockDuration,
1✔
2183
        )
1✔
2184
        if err != nil {
1✔
2185
                return nil, fmt.Errorf("could not lock inputs: %w", err)
×
2186
        }
×
2187

2188
        // Convert the lock leases to the RPC format.
2189
        rpcLocks := marshallLeases(locks)
1✔
2190

1✔
2191
        return &FundPsbtResponse{
1✔
2192
                FundedPsbt:        buf.Bytes(),
1✔
2193
                ChangeOutputIndex: changeIndex,
1✔
2194
                LockedUtxos:       rpcLocks,
1✔
2195
        }, nil
1✔
2196
}
2197

2198
// handleChange is a closure that either adds the non-zero change amount to an
2199
// existing output or creates a change output. The function returns the new
2200
// change output index if a new change output was added.
2201
func (w *WalletKit) handleChange(packet *psbt.Packet, changeIndex int32,
2202
        changeAmount int64, changeType chanfunding.ChangeAddressType,
2203
        changeAccount string) (int32, error) {
1✔
2204

1✔
2205
        // Does an existing output get the change?
1✔
2206
        if changeIndex >= 0 {
2✔
2207
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
1✔
2208
                changeOut.Value += changeAmount
1✔
2209

1✔
2210
                return changeIndex, nil
1✔
2211
        }
1✔
2212

2213
        // The user requested a new change output.
2214
        addrType := addrTypeFromChangeAddressType(changeType)
×
2215
        changeAddr, err := w.cfg.Wallet.NewAddress(
×
2216
                addrType, true, changeAccount,
×
2217
        )
×
2218
        if err != nil {
×
2219
                return 0, fmt.Errorf("could not derive change address: %w", err)
×
2220
        }
×
2221

2222
        changeScript, err := txscript.PayToAddrScript(changeAddr)
×
2223
        if err != nil {
×
2224
                return 0, fmt.Errorf("could not derive change script: %w", err)
×
2225
        }
×
2226

2227
        // We need to add the derivation info for the change address in case it
2228
        // is a P2TR address. This is mostly to prove it's a bare BIP-0086
2229
        // address, which is required for some protocols (such as Taproot
2230
        // Assets).
2231
        pOut := psbt.POutput{}
×
2232
        _, isTaprootChangeAddr := changeAddr.(*btcutil.AddressTaproot)
×
2233
        if isTaprootChangeAddr {
×
2234
                changeAddrInfo, err := w.cfg.Wallet.AddressInfo(changeAddr)
×
2235
                if err != nil {
×
2236
                        return 0, fmt.Errorf("could not get address info: %w",
×
2237
                                err)
×
2238
                }
×
2239

2240
                deriv, trDeriv, _, err := btcwallet.Bip32DerivationFromAddress(
×
2241
                        changeAddrInfo,
×
2242
                )
×
2243
                if err != nil {
×
2244
                        return 0, fmt.Errorf("could not get derivation info: "+
×
2245
                                "%w", err)
×
2246
                }
×
2247

2248
                pOut.TaprootInternalKey = trDeriv.XOnlyPubKey
×
2249
                pOut.Bip32Derivation = []*psbt.Bip32Derivation{deriv}
×
2250
                pOut.TaprootBip32Derivation = []*psbt.TaprootBip32Derivation{
×
2251
                        trDeriv,
×
2252
                }
×
2253
        }
2254

2255
        newChangeIndex := int32(len(packet.Outputs))
×
2256
        packet.UnsignedTx.TxOut = append(
×
2257
                packet.UnsignedTx.TxOut, &wire.TxOut{
×
2258
                        Value:    changeAmount,
×
2259
                        PkScript: changeScript,
×
2260
                },
×
2261
        )
×
2262
        packet.Outputs = append(packet.Outputs, pOut)
×
2263

×
2264
        return newChangeIndex, nil
×
2265
}
2266

2267
// marshallLeases converts the lock leases to the RPC format.
2268
func marshallLeases(locks []*base.ListLeasedOutputResult) []*UtxoLease {
1✔
2269
        rpcLocks := make([]*UtxoLease, len(locks))
1✔
2270
        for idx, lock := range locks {
2✔
2271
                lock := lock
1✔
2272

1✔
2273
                rpcLocks[idx] = &UtxoLease{
1✔
2274
                        Id:         lock.LockID[:],
1✔
2275
                        Outpoint:   lnrpc.MarshalOutPoint(&lock.Outpoint),
1✔
2276
                        Expiration: uint64(lock.Expiration.Unix()),
1✔
2277
                        PkScript:   lock.PkScript,
1✔
2278
                        Value:      uint64(lock.Value),
1✔
2279
                }
1✔
2280
        }
1✔
2281

2282
        return rpcLocks
1✔
2283
}
2284

2285
// keyScopeFromChangeAddressType maps a ChangeAddressType from protobuf to a
2286
// KeyScope. If the type is ChangeAddressType_CHANGE_ADDRESS_TYPE_UNSPECIFIED,
2287
// it returns nil.
2288
func keyScopeFromChangeAddressType(
2289
        changeAddressType ChangeAddressType) *waddrmgr.KeyScope {
1✔
2290

1✔
2291
        switch changeAddressType {
1✔
2292
        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
1✔
2293
                return &waddrmgr.KeyScopeBIP0086
1✔
2294

2295
        default:
1✔
2296
                return nil
1✔
2297
        }
2298
}
2299

2300
// addrTypeFromChangeAddressType maps a chanfunding.ChangeAddressType to the
2301
// lnwallet.AddressType.
2302
func addrTypeFromChangeAddressType(
2303
        changeAddressType chanfunding.ChangeAddressType) lnwallet.AddressType {
×
2304

×
2305
        switch changeAddressType {
×
2306
        case chanfunding.P2TRChangeAddress:
×
2307
                return lnwallet.TaprootPubkey
×
2308

2309
        default:
×
2310
                return lnwallet.WitnessPubKey
×
2311
        }
2312
}
2313

2314
// SignPsbt expects a partial transaction with all inputs and outputs fully
2315
// declared and tries to sign all unsigned inputs that have all required fields
2316
// (UTXO information, BIP32 derivation information, witness or sig scripts)
2317
// set.
2318
// If no error is returned, the PSBT is ready to be given to the next signer or
2319
// to be finalized if lnd was the last signer.
2320
//
2321
// NOTE: This RPC only signs inputs (and only those it can sign), it does not
2322
// perform any other tasks (such as coin selection, UTXO locking or
2323
// input/output/fee value validation, PSBT finalization). Any input that is
2324
// incomplete will be skipped.
2325
func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) (
2326
        *SignPsbtResponse, error) {
1✔
2327

1✔
2328
        packet, err := psbt.NewFromRawBytes(
1✔
2329
                bytes.NewReader(req.FundedPsbt), false,
1✔
2330
        )
1✔
2331
        if err != nil {
1✔
2332
                log.Debugf("Error parsing PSBT: %v, raw input: %x", err,
×
2333
                        req.FundedPsbt)
×
2334
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
2335
        }
×
2336

2337
        // Before we attempt to sign the packet, ensure that every input either
2338
        // has a witness UTXO, or a non witness UTXO.
2339
        for idx := range packet.UnsignedTx.TxIn {
2✔
2340
                in := packet.Inputs[idx]
1✔
2341

1✔
2342
                // Doesn't have either a witness or non witness UTXO so we need
1✔
2343
                // to exit here as otherwise signing will fail.
1✔
2344
                if in.WitnessUtxo == nil && in.NonWitnessUtxo == nil {
2✔
2345
                        return nil, fmt.Errorf("input (index=%v) doesn't "+
1✔
2346
                                "specify any UTXO info", idx)
1✔
2347
                }
1✔
2348
        }
2349

2350
        // Let the wallet do the heavy lifting. This will sign all inputs that
2351
        // we have the UTXO for. If some inputs can't be signed and don't have
2352
        // witness data attached, they will just be skipped.
2353
        signedInputs, err := w.cfg.Wallet.SignPsbt(packet)
1✔
2354
        if err != nil {
1✔
2355
                return nil, fmt.Errorf("error signing PSBT: %w", err)
×
2356
        }
×
2357

2358
        // Serialize the signed PSBT in both the packet and wire format.
2359
        var signedPsbtBytes bytes.Buffer
1✔
2360
        err = packet.Serialize(&signedPsbtBytes)
1✔
2361
        if err != nil {
1✔
2362
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
2363
        }
×
2364

2365
        return &SignPsbtResponse{
1✔
2366
                SignedPsbt:   signedPsbtBytes.Bytes(),
1✔
2367
                SignedInputs: signedInputs,
1✔
2368
        }, nil
1✔
2369
}
2370

2371
// FinalizePsbt expects a partial transaction with all inputs and outputs fully
2372
// declared and tries to sign all inputs that belong to the wallet. Lnd must be
2373
// the last signer of the transaction. That means, if there are any unsigned
2374
// non-witness inputs or inputs without UTXO information attached or inputs
2375
// without witness data that do not belong to lnd's wallet, this method will
2376
// fail. If no error is returned, the PSBT is ready to be extracted and the
2377
// final TX within to be broadcast.
2378
//
2379
// NOTE: This method does NOT publish the transaction once finalized. It is the
2380
// caller's responsibility to either publish the transaction on success or
2381
// unlock/release any locked UTXOs in case of an error in this method.
2382
func (w *WalletKit) FinalizePsbt(_ context.Context,
2383
        req *FinalizePsbtRequest) (*FinalizePsbtResponse, error) {
1✔
2384

1✔
2385
        // We'll assume the PSBT was funded by the default account unless
1✔
2386
        // otherwise specified.
1✔
2387
        account := lnwallet.DefaultAccountName
1✔
2388
        if req.Account != "" {
1✔
2389
                account = req.Account
×
2390
        }
×
2391

2392
        // Parse the funded PSBT.
2393
        packet, err := psbt.NewFromRawBytes(
1✔
2394
                bytes.NewReader(req.FundedPsbt), false,
1✔
2395
        )
1✔
2396
        if err != nil {
1✔
2397
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
2398
        }
×
2399

2400
        // The only check done at this level is to validate that the PSBT is
2401
        // not complete. The wallet performs all other checks.
2402
        if packet.IsComplete() {
1✔
2403
                return nil, fmt.Errorf("PSBT is already fully signed")
×
2404
        }
×
2405

2406
        // Let the wallet do the heavy lifting. This will sign all inputs that
2407
        // we have the UTXO for. If some inputs can't be signed and don't have
2408
        // witness data attached, this will fail.
2409
        err = w.cfg.Wallet.FinalizePsbt(packet, account)
1✔
2410
        if err != nil {
1✔
2411
                return nil, fmt.Errorf("error finalizing PSBT: %w", err)
×
2412
        }
×
2413

2414
        var (
1✔
2415
                finalPsbtBytes bytes.Buffer
1✔
2416
                finalTxBytes   bytes.Buffer
1✔
2417
        )
1✔
2418

1✔
2419
        // Serialize the finalized PSBT in both the packet and wire format.
1✔
2420
        err = packet.Serialize(&finalPsbtBytes)
1✔
2421
        if err != nil {
1✔
2422
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
2423
        }
×
2424
        finalTx, err := psbt.Extract(packet)
1✔
2425
        if err != nil {
1✔
2426
                return nil, fmt.Errorf("unable to extract final TX: %w", err)
×
2427
        }
×
2428
        err = finalTx.Serialize(&finalTxBytes)
1✔
2429
        if err != nil {
1✔
2430
                return nil, fmt.Errorf("error serializing final TX: %w", err)
×
2431
        }
×
2432

2433
        return &FinalizePsbtResponse{
1✔
2434
                SignedPsbt: finalPsbtBytes.Bytes(),
1✔
2435
                RawFinalTx: finalTxBytes.Bytes(),
1✔
2436
        }, nil
1✔
2437
}
2438

2439
// marshalWalletAccount converts the properties of an account into its RPC
2440
// representation.
2441
func marshalWalletAccount(internalScope waddrmgr.KeyScope,
2442
        account *waddrmgr.AccountProperties) (*Account, error) {
1✔
2443

1✔
2444
        var addrType AddressType
1✔
2445
        switch account.KeyScope {
1✔
2446
        case waddrmgr.KeyScopeBIP0049Plus:
1✔
2447
                // No address schema present represents the traditional BIP-0049
1✔
2448
                // address derivation scheme.
1✔
2449
                if account.AddrSchema == nil {
2✔
2450
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
1✔
2451
                        break
1✔
2452
                }
2453

2454
                switch *account.AddrSchema {
1✔
2455
                case waddrmgr.KeyScopeBIP0049AddrSchema:
1✔
2456
                        addrType = AddressType_NESTED_WITNESS_PUBKEY_HASH
1✔
2457

2458
                case waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0049Plus]:
1✔
2459
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
1✔
2460

2461
                default:
×
2462
                        return nil, fmt.Errorf("unsupported address schema %v",
×
2463
                                *account.AddrSchema)
×
2464
                }
2465

2466
        case waddrmgr.KeyScopeBIP0084:
1✔
2467
                addrType = AddressType_WITNESS_PUBKEY_HASH
1✔
2468

2469
        case waddrmgr.KeyScopeBIP0086:
1✔
2470
                addrType = AddressType_TAPROOT_PUBKEY
1✔
2471

2472
        case internalScope:
1✔
2473
                addrType = AddressType_WITNESS_PUBKEY_HASH
1✔
2474

2475
        default:
×
2476
                return nil, fmt.Errorf("account %v has unsupported "+
×
2477
                        "key scope %v", account.AccountName, account.KeyScope)
×
2478
        }
2479

2480
        rpcAccount := &Account{
1✔
2481
                Name:             account.AccountName,
1✔
2482
                AddressType:      addrType,
1✔
2483
                ExternalKeyCount: account.ExternalKeyCount,
1✔
2484
                InternalKeyCount: account.InternalKeyCount,
1✔
2485
                WatchOnly:        account.IsWatchOnly,
1✔
2486
        }
1✔
2487

1✔
2488
        // The remaining fields can only be done on accounts other than the
1✔
2489
        // default imported one existing within each key scope.
1✔
2490
        if account.AccountName != waddrmgr.ImportedAddrAccountName {
2✔
2491
                nonHardenedIndex := account.AccountPubKey.ChildIndex() -
1✔
2492
                        hdkeychain.HardenedKeyStart
1✔
2493
                rpcAccount.ExtendedPublicKey = account.AccountPubKey.String()
1✔
2494
                if account.MasterKeyFingerprint != 0 {
1✔
2495
                        var mkfp [4]byte
×
2496
                        binary.BigEndian.PutUint32(
×
2497
                                mkfp[:], account.MasterKeyFingerprint,
×
2498
                        )
×
2499
                        rpcAccount.MasterKeyFingerprint = mkfp[:]
×
2500
                }
×
2501
                rpcAccount.DerivationPath = fmt.Sprintf("%v/%v'",
1✔
2502
                        account.KeyScope, nonHardenedIndex)
1✔
2503
        }
2504

2505
        return rpcAccount, nil
1✔
2506
}
2507

2508
// marshalWalletAddressList converts the list of address into its RPC
2509
// representation.
2510
func marshalWalletAddressList(w *WalletKit, account *waddrmgr.AccountProperties,
2511
        addressList []lnwallet.AddressProperty) (*AccountWithAddresses, error) {
1✔
2512

1✔
2513
        // Get the RPC representation of account.
1✔
2514
        rpcAccount, err := marshalWalletAccount(
1✔
2515
                w.internalScope(), account,
1✔
2516
        )
1✔
2517
        if err != nil {
1✔
2518
                return nil, err
×
2519
        }
×
2520

2521
        addresses := make([]*AddressProperty, len(addressList))
1✔
2522
        for idx, addr := range addressList {
2✔
2523
                var pubKeyBytes []byte
1✔
2524
                if addr.PublicKey != nil {
2✔
2525
                        pubKeyBytes = addr.PublicKey.SerializeCompressed()
1✔
2526
                }
1✔
2527
                addresses[idx] = &AddressProperty{
1✔
2528
                        Address:        addr.Address,
1✔
2529
                        IsInternal:     addr.Internal,
1✔
2530
                        Balance:        int64(addr.Balance),
1✔
2531
                        DerivationPath: addr.DerivationPath,
1✔
2532
                        PublicKey:      pubKeyBytes,
1✔
2533
                }
1✔
2534
        }
2535

2536
        rpcAddressList := &AccountWithAddresses{
1✔
2537
                Name:           rpcAccount.Name,
1✔
2538
                AddressType:    rpcAccount.AddressType,
1✔
2539
                DerivationPath: rpcAccount.DerivationPath,
1✔
2540
                Addresses:      addresses,
1✔
2541
        }
1✔
2542

1✔
2543
        return rpcAddressList, nil
1✔
2544
}
2545

2546
// ListAccounts retrieves all accounts belonging to the wallet by default. A
2547
// name and key scope filter can be provided to filter through all of the wallet
2548
// accounts and return only those matching.
2549
func (w *WalletKit) ListAccounts(ctx context.Context,
2550
        req *ListAccountsRequest) (*ListAccountsResponse, error) {
1✔
2551

1✔
2552
        // Map the supported address types into their corresponding key scope.
1✔
2553
        var keyScopeFilter *waddrmgr.KeyScope
1✔
2554
        switch req.AddressType {
1✔
2555
        case AddressType_UNKNOWN:
1✔
2556
                break
1✔
2557

2558
        case AddressType_WITNESS_PUBKEY_HASH:
1✔
2559
                keyScope := waddrmgr.KeyScopeBIP0084
1✔
2560
                keyScopeFilter = &keyScope
1✔
2561

2562
        case AddressType_NESTED_WITNESS_PUBKEY_HASH,
2563
                AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
1✔
2564

1✔
2565
                keyScope := waddrmgr.KeyScopeBIP0049Plus
1✔
2566
                keyScopeFilter = &keyScope
1✔
2567

2568
        case AddressType_TAPROOT_PUBKEY:
1✔
2569
                keyScope := waddrmgr.KeyScopeBIP0086
1✔
2570
                keyScopeFilter = &keyScope
1✔
2571

2572
        default:
×
2573
                return nil, fmt.Errorf("unhandled address type %v",
×
2574
                        req.AddressType)
×
2575
        }
2576

2577
        accounts, err := w.cfg.Wallet.ListAccounts(req.Name, keyScopeFilter)
1✔
2578
        if err != nil {
1✔
2579
                return nil, err
×
2580
        }
×
2581

2582
        rpcAccounts := make([]*Account, 0, len(accounts))
1✔
2583
        for _, account := range accounts {
2✔
2584
                // Don't include the default imported accounts created by the
1✔
2585
                // wallet in the response if they don't have any keys imported.
1✔
2586
                if account.AccountName == waddrmgr.ImportedAddrAccountName &&
1✔
2587
                        account.ImportedKeyCount == 0 {
2✔
2588

1✔
2589
                        continue
1✔
2590
                }
2591

2592
                rpcAccount, err := marshalWalletAccount(
1✔
2593
                        w.internalScope(), account,
1✔
2594
                )
1✔
2595
                if err != nil {
1✔
2596
                        return nil, err
×
2597
                }
×
2598
                rpcAccounts = append(rpcAccounts, rpcAccount)
1✔
2599
        }
2600

2601
        return &ListAccountsResponse{Accounts: rpcAccounts}, nil
1✔
2602
}
2603

2604
// RequiredReserve returns the minimum amount of satoshis that should be
2605
// kept in the wallet in order to fee bump anchor channels if necessary.
2606
// The value scales with the number of public anchor channels but is
2607
// capped at a maximum.
2608
func (w *WalletKit) RequiredReserve(ctx context.Context,
2609
        req *RequiredReserveRequest) (*RequiredReserveResponse, error) {
1✔
2610

1✔
2611
        numAnchorChans, err := w.cfg.CurrentNumAnchorChans()
1✔
2612
        if err != nil {
1✔
2613
                return nil, err
×
2614
        }
×
2615

2616
        additionalChans := req.AdditionalPublicChannels
1✔
2617
        totalChans := uint32(numAnchorChans) + additionalChans
1✔
2618
        reserved := w.cfg.Wallet.RequiredReserve(totalChans)
1✔
2619

1✔
2620
        return &RequiredReserveResponse{
1✔
2621
                RequiredReserve: int64(reserved),
1✔
2622
        }, nil
1✔
2623
}
2624

2625
// ListAddresses retrieves all the addresses along with their balance. An
2626
// account name filter can be provided to filter through all of the
2627
// wallet accounts and return the addresses of only those matching.
2628
func (w *WalletKit) ListAddresses(ctx context.Context,
2629
        req *ListAddressesRequest) (*ListAddressesResponse, error) {
1✔
2630

1✔
2631
        addressLists, err := w.cfg.Wallet.ListAddresses(
1✔
2632
                req.AccountName,
1✔
2633
                req.ShowCustomAccounts,
1✔
2634
        )
1✔
2635
        if err != nil {
1✔
2636
                return nil, err
×
2637
        }
×
2638

2639
        // Create a slice of accounts from addressLists map.
2640
        accounts := make([]*waddrmgr.AccountProperties, 0, len(addressLists))
1✔
2641
        for account := range addressLists {
2✔
2642
                accounts = append(accounts, account)
1✔
2643
        }
1✔
2644

2645
        // Sort the accounts by derivation path.
2646
        sort.Slice(accounts, func(i, j int) bool {
2✔
2647
                scopeI := accounts[i].KeyScope
1✔
2648
                scopeJ := accounts[j].KeyScope
1✔
2649
                if scopeI.Purpose == scopeJ.Purpose {
1✔
2650
                        if scopeI.Coin == scopeJ.Coin {
×
2651
                                acntNumI := accounts[i].AccountNumber
×
2652
                                acntNumJ := accounts[j].AccountNumber
×
2653
                                return acntNumI < acntNumJ
×
2654
                        }
×
2655

2656
                        return scopeI.Coin < scopeJ.Coin
×
2657
                }
2658

2659
                return scopeI.Purpose < scopeJ.Purpose
1✔
2660
        })
2661

2662
        rpcAddressLists := make([]*AccountWithAddresses, 0, len(addressLists))
1✔
2663
        for _, account := range accounts {
2✔
2664
                addressList := addressLists[account]
1✔
2665
                rpcAddressList, err := marshalWalletAddressList(
1✔
2666
                        w, account, addressList,
1✔
2667
                )
1✔
2668
                if err != nil {
1✔
2669
                        return nil, err
×
2670
                }
×
2671

2672
                rpcAddressLists = append(rpcAddressLists, rpcAddressList)
1✔
2673
        }
2674

2675
        return &ListAddressesResponse{
1✔
2676
                AccountWithAddresses: rpcAddressLists,
1✔
2677
        }, nil
1✔
2678
}
2679

2680
// parseAddrType parses an address type from its RPC representation to a
2681
// *waddrmgr.AddressType.
2682
func parseAddrType(addrType AddressType,
2683
        required bool) (*waddrmgr.AddressType, error) {
1✔
2684

1✔
2685
        switch addrType {
1✔
2686
        case AddressType_UNKNOWN:
×
2687
                if required {
×
2688
                        return nil, fmt.Errorf("an address type must be " +
×
2689
                                "specified")
×
2690
                }
×
2691
                return nil, nil
×
2692

2693
        case AddressType_WITNESS_PUBKEY_HASH:
1✔
2694
                addrTyp := waddrmgr.WitnessPubKey
1✔
2695
                return &addrTyp, nil
1✔
2696

2697
        case AddressType_NESTED_WITNESS_PUBKEY_HASH:
1✔
2698
                addrTyp := waddrmgr.NestedWitnessPubKey
1✔
2699
                return &addrTyp, nil
1✔
2700

2701
        case AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
1✔
2702
                addrTyp := waddrmgr.WitnessPubKey
1✔
2703
                return &addrTyp, nil
1✔
2704

2705
        case AddressType_TAPROOT_PUBKEY:
1✔
2706
                addrTyp := waddrmgr.TaprootPubKey
1✔
2707
                return &addrTyp, nil
1✔
2708

2709
        default:
×
2710
                return nil, fmt.Errorf("unhandled address type %v", addrType)
×
2711
        }
2712
}
2713

2714
// msgSignaturePrefix is a prefix used to prevent inadvertently signing a
2715
// transaction or a signature. It is prepended in front of the message and
2716
// follows the same standard as bitcoin core and btcd.
2717
const msgSignaturePrefix = "Bitcoin Signed Message:\n"
2718

2719
// SignMessageWithAddr signs a message with the private key of the provided
2720
// address. The address needs to belong to the lnd wallet.
2721
func (w *WalletKit) SignMessageWithAddr(_ context.Context,
2722
        req *SignMessageWithAddrRequest) (*SignMessageWithAddrResponse, error) {
1✔
2723

1✔
2724
        addr, err := btcutil.DecodeAddress(req.Addr, w.cfg.ChainParams)
1✔
2725
        if err != nil {
1✔
2726
                return nil, fmt.Errorf("unable to decode address: %w", err)
×
2727
        }
×
2728

2729
        if !addr.IsForNet(w.cfg.ChainParams) {
1✔
2730
                return nil, fmt.Errorf("encoded address is for "+
×
2731
                        "the wrong network %s", req.Addr)
×
2732
        }
×
2733

2734
        // Fetch address infos from own wallet and check whether it belongs
2735
        // to the lnd wallet.
2736
        managedAddr, err := w.cfg.Wallet.AddressInfo(addr)
1✔
2737
        if err != nil {
1✔
2738
                return nil, fmt.Errorf("address could not be found in the "+
×
2739
                        "wallet database: %w", err)
×
2740
        }
×
2741

2742
        // Verifying by checking the interface type that the wallet knows about
2743
        // the public and private keys so it can sign the message with the
2744
        // private key of this address.
2745
        pubKey, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
1✔
2746
        if !ok {
1✔
2747
                return nil, fmt.Errorf("private key to address is unknown")
×
2748
        }
×
2749

2750
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
1✔
2751
        if err != nil {
1✔
2752
                return nil, err
×
2753
        }
×
2754

2755
        // For all address types (P2WKH, NP2WKH,P2TR) the ECDSA compact signing
2756
        // algorithm is used. For P2TR addresses this represents a special case.
2757
        // ECDSA is used to create a compact signature which makes the public
2758
        // key of the signature recoverable. For Schnorr no known compact
2759
        // signing algorithm exists yet.
2760
        privKey, err := pubKey.PrivKey()
1✔
2761
        if err != nil {
1✔
2762
                return nil, fmt.Errorf("no private key could be "+
×
2763
                        "fetched from wallet database: %w", err)
×
2764
        }
×
2765

2766
        sigBytes := ecdsa.SignCompact(privKey, digest, pubKey.Compressed())
1✔
2767

1✔
2768
        // Bitcoin signatures are base64 encoded (being compatible with
1✔
2769
        // bitcoin-core and btcd).
1✔
2770
        sig := base64.StdEncoding.EncodeToString(sigBytes)
1✔
2771

1✔
2772
        return &SignMessageWithAddrResponse{
1✔
2773
                Signature: sig,
1✔
2774
        }, nil
1✔
2775
}
2776

2777
// VerifyMessageWithAddr verifies a signature on a message with a provided
2778
// address, it checks both the validity of the signature itself and then
2779
// verifies whether the signature corresponds to the public key of the
2780
// provided address. There is no dependence on the private key of the address
2781
// therefore also external addresses are allowed to verify signatures.
2782
// Supported address types are P2PKH, P2WKH, NP2WKH, P2TR.
2783
func (w *WalletKit) VerifyMessageWithAddr(_ context.Context,
2784
        req *VerifyMessageWithAddrRequest) (*VerifyMessageWithAddrResponse,
2785
        error) {
1✔
2786

1✔
2787
        sig, err := base64.StdEncoding.DecodeString(req.Signature)
1✔
2788
        if err != nil {
1✔
2789
                return nil, fmt.Errorf("malformed base64 encoding of "+
×
2790
                        "the signature: %w", err)
×
2791
        }
×
2792

2793
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
1✔
2794
        if err != nil {
1✔
2795
                return nil, err
×
2796
        }
×
2797

2798
        pk, wasCompressed, err := ecdsa.RecoverCompact(sig, digest)
1✔
2799
        if err != nil {
1✔
2800
                return nil, fmt.Errorf("unable to recover public key "+
×
2801
                        "from compact signature: %w", err)
×
2802
        }
×
2803

2804
        var serializedPubkey []byte
1✔
2805
        if wasCompressed {
2✔
2806
                serializedPubkey = pk.SerializeCompressed()
1✔
2807
        } else {
1✔
2808
                serializedPubkey = pk.SerializeUncompressed()
×
2809
        }
×
2810

2811
        addr, err := btcutil.DecodeAddress(req.Addr, w.cfg.ChainParams)
1✔
2812
        if err != nil {
1✔
2813
                return nil, fmt.Errorf("unable to decode address: %w", err)
×
2814
        }
×
2815

2816
        if !addr.IsForNet(w.cfg.ChainParams) {
1✔
2817
                return nil, fmt.Errorf("encoded address is for"+
×
2818
                        "the wrong network %s", req.Addr)
×
2819
        }
×
2820

2821
        var (
1✔
2822
                address    btcutil.Address
1✔
2823
                pubKeyHash = btcutil.Hash160(serializedPubkey)
1✔
2824
        )
1✔
2825

1✔
2826
        // Ensure the address is one of the supported types.
1✔
2827
        switch addr.(type) {
1✔
2828
        case *btcutil.AddressPubKeyHash:
1✔
2829
                address, err = btcutil.NewAddressPubKeyHash(
1✔
2830
                        pubKeyHash, w.cfg.ChainParams,
1✔
2831
                )
1✔
2832
                if err != nil {
1✔
2833
                        return nil, err
×
2834
                }
×
2835

2836
        case *btcutil.AddressWitnessPubKeyHash:
1✔
2837
                address, err = btcutil.NewAddressWitnessPubKeyHash(
1✔
2838
                        pubKeyHash, w.cfg.ChainParams,
1✔
2839
                )
1✔
2840
                if err != nil {
1✔
2841
                        return nil, err
×
2842
                }
×
2843

2844
        case *btcutil.AddressScriptHash:
1✔
2845
                // Check if address is a Nested P2WKH (NP2WKH).
1✔
2846
                address, err = btcutil.NewAddressWitnessPubKeyHash(
1✔
2847
                        pubKeyHash, w.cfg.ChainParams,
1✔
2848
                )
1✔
2849
                if err != nil {
1✔
2850
                        return nil, err
×
2851
                }
×
2852

2853
                witnessScript, err := txscript.PayToAddrScript(address)
1✔
2854
                if err != nil {
1✔
2855
                        return nil, err
×
2856
                }
×
2857

2858
                address, err = btcutil.NewAddressScriptHashFromHash(
1✔
2859
                        btcutil.Hash160(witnessScript), w.cfg.ChainParams,
1✔
2860
                )
1✔
2861
                if err != nil {
1✔
2862
                        return nil, err
×
2863
                }
×
2864

2865
        case *btcutil.AddressTaproot:
1✔
2866
                // Only addresses without a tapscript are allowed because
1✔
2867
                // the verification is using the internal key.
1✔
2868
                tapKey := txscript.ComputeTaprootKeyNoScript(pk)
1✔
2869
                address, err = btcutil.NewAddressTaproot(
1✔
2870
                        schnorr.SerializePubKey(tapKey),
1✔
2871
                        w.cfg.ChainParams,
1✔
2872
                )
1✔
2873
                if err != nil {
1✔
2874
                        return nil, err
×
2875
                }
×
2876

2877
        default:
×
2878
                return nil, fmt.Errorf("unsupported address type")
×
2879
        }
2880

2881
        return &VerifyMessageWithAddrResponse{
1✔
2882
                Valid:  req.Addr == address.EncodeAddress(),
1✔
2883
                Pubkey: serializedPubkey,
1✔
2884
        }, nil
1✔
2885
}
2886

2887
// ImportAccount imports an account backed by an account extended public key.
2888
// The master key fingerprint denotes the fingerprint of the root key
2889
// corresponding to the account public key (also known as the key with
2890
// derivation path m/). This may be required by some hardware wallets for proper
2891
// identification and signing.
2892
//
2893
// The address type can usually be inferred from the key's version, but may be
2894
// required for certain keys to map them into the proper scope.
2895
//
2896
// For BIP-0044 keys, an address type must be specified as we intend to not
2897
// support importing BIP-0044 keys into the wallet using the legacy
2898
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force
2899
// the standard BIP-0049 derivation scheme, while a witness address type will
2900
// force the standard BIP-0084 derivation scheme.
2901
//
2902
// For BIP-0049 keys, an address type must also be specified to make a
2903
// distinction between the standard BIP-0049 address schema (nested witness
2904
// pubkeys everywhere) and our own BIP-0049Plus address schema (nested pubkeys
2905
// externally, witness pubkeys internally).
2906
func (w *WalletKit) ImportAccount(_ context.Context,
2907
        req *ImportAccountRequest) (*ImportAccountResponse, error) {
1✔
2908

1✔
2909
        accountPubKey, err := hdkeychain.NewKeyFromString(req.ExtendedPublicKey)
1✔
2910
        if err != nil {
1✔
2911
                return nil, err
×
2912
        }
×
2913

2914
        var mkfp uint32
1✔
2915
        switch len(req.MasterKeyFingerprint) {
1✔
2916
        // No master key fingerprint provided, which is fine as it's not
2917
        // required.
2918
        case 0:
1✔
2919
        // Expected length.
2920
        case 4:
×
2921
                mkfp = binary.BigEndian.Uint32(req.MasterKeyFingerprint)
×
2922
        default:
×
2923
                return nil, errors.New("invalid length for master key " +
×
2924
                        "fingerprint, expected 4 bytes in big-endian")
×
2925
        }
2926

2927
        addrType, err := parseAddrType(req.AddressType, false)
1✔
2928
        if err != nil {
1✔
2929
                return nil, err
×
2930
        }
×
2931

2932
        accountProps, extAddrs, intAddrs, err := w.cfg.Wallet.ImportAccount(
1✔
2933
                req.Name, accountPubKey, mkfp, addrType, req.DryRun,
1✔
2934
        )
1✔
2935
        if err != nil {
2✔
2936
                return nil, err
1✔
2937
        }
1✔
2938

2939
        rpcAccount, err := marshalWalletAccount(w.internalScope(), accountProps)
1✔
2940
        if err != nil {
1✔
2941
                return nil, err
×
2942
        }
×
2943

2944
        resp := &ImportAccountResponse{Account: rpcAccount}
1✔
2945
        if !req.DryRun {
2✔
2946
                return resp, nil
1✔
2947
        }
1✔
2948

2949
        resp.DryRunExternalAddrs = make([]string, len(extAddrs))
×
2950
        for i := 0; i < len(extAddrs); i++ {
×
2951
                resp.DryRunExternalAddrs[i] = extAddrs[i].String()
×
2952
        }
×
2953
        resp.DryRunInternalAddrs = make([]string, len(intAddrs))
×
2954
        for i := 0; i < len(intAddrs); i++ {
×
2955
                resp.DryRunInternalAddrs[i] = intAddrs[i].String()
×
2956
        }
×
2957

2958
        return resp, nil
×
2959
}
2960

2961
// ImportPublicKey imports a single derived public key into the wallet. The
2962
// address type can usually be inferred from the key's version, but in the case
2963
// of legacy versions (xpub, tpub), an address type must be specified as we
2964
// intend to not support importing BIP-44 keys into the wallet using the legacy
2965
// pay-to-pubkey-hash (P2PKH) scheme. For Taproot keys, this will only watch
2966
// the BIP-0086 style output script. Use ImportTapscript for more advanced key
2967
// spend or script spend outputs.
2968
func (w *WalletKit) ImportPublicKey(_ context.Context,
2969
        req *ImportPublicKeyRequest) (*ImportPublicKeyResponse, error) {
1✔
2970

1✔
2971
        var (
1✔
2972
                pubKey *btcec.PublicKey
1✔
2973
                err    error
1✔
2974
        )
1✔
2975
        switch req.AddressType {
1✔
2976
        case AddressType_TAPROOT_PUBKEY:
1✔
2977
                pubKey, err = schnorr.ParsePubKey(req.PublicKey)
1✔
2978

2979
        default:
1✔
2980
                pubKey, err = btcec.ParsePubKey(req.PublicKey)
1✔
2981
        }
2982
        if err != nil {
1✔
2983
                return nil, err
×
2984
        }
×
2985

2986
        addrType, err := parseAddrType(req.AddressType, true)
1✔
2987
        if err != nil {
1✔
2988
                return nil, err
×
2989
        }
×
2990

2991
        if err := w.cfg.Wallet.ImportPublicKey(pubKey, *addrType); err != nil {
1✔
2992
                return nil, err
×
2993
        }
×
2994

2995
        return &ImportPublicKeyResponse{
1✔
2996
                Status: fmt.Sprintf("public key %x imported",
1✔
2997
                        pubKey.SerializeCompressed()),
1✔
2998
        }, nil
1✔
2999
}
3000

3001
// ImportTapscript imports a Taproot script and internal key and adds the
3002
// resulting Taproot output key as a watch-only output script into the wallet.
3003
// For BIP-0086 style Taproot keys (no root hash commitment and no script spend
3004
// path) use ImportPublicKey.
3005
//
3006
// NOTE: Taproot keys imported through this RPC currently _cannot_ be used for
3007
// funding PSBTs. Only tracking the balance and UTXOs is currently supported.
3008
func (w *WalletKit) ImportTapscript(_ context.Context,
3009
        req *ImportTapscriptRequest) (*ImportTapscriptResponse, error) {
1✔
3010

1✔
3011
        internalKey, err := schnorr.ParsePubKey(req.InternalPublicKey)
1✔
3012
        if err != nil {
1✔
3013
                return nil, fmt.Errorf("error parsing internal key: %w", err)
×
3014
        }
×
3015

3016
        var tapscript *waddrmgr.Tapscript
1✔
3017
        switch {
1✔
3018
        case req.GetFullTree() != nil:
1✔
3019
                tree := req.GetFullTree()
1✔
3020
                leaves := make([]txscript.TapLeaf, len(tree.AllLeaves))
1✔
3021
                for idx, leaf := range tree.AllLeaves {
2✔
3022
                        leaves[idx] = txscript.TapLeaf{
1✔
3023
                                LeafVersion: txscript.TapscriptLeafVersion(
1✔
3024
                                        leaf.LeafVersion,
1✔
3025
                                ),
1✔
3026
                                Script: leaf.Script,
1✔
3027
                        }
1✔
3028
                }
1✔
3029

3030
                tapscript = input.TapscriptFullTree(internalKey, leaves...)
1✔
3031

3032
        case req.GetPartialReveal() != nil:
1✔
3033
                partialReveal := req.GetPartialReveal()
1✔
3034
                if partialReveal.RevealedLeaf == nil {
1✔
3035
                        return nil, fmt.Errorf("missing revealed leaf")
×
3036
                }
×
3037

3038
                revealedLeaf := txscript.TapLeaf{
1✔
3039
                        LeafVersion: txscript.TapscriptLeafVersion(
1✔
3040
                                partialReveal.RevealedLeaf.LeafVersion,
1✔
3041
                        ),
1✔
3042
                        Script: partialReveal.RevealedLeaf.Script,
1✔
3043
                }
1✔
3044
                if len(partialReveal.FullInclusionProof)%32 != 0 {
1✔
3045
                        return nil, fmt.Errorf("invalid inclusion proof "+
×
3046
                                "length, expected multiple of 32, got %d",
×
3047
                                len(partialReveal.FullInclusionProof)%32)
×
3048
                }
×
3049

3050
                tapscript = input.TapscriptPartialReveal(
1✔
3051
                        internalKey, revealedLeaf,
1✔
3052
                        partialReveal.FullInclusionProof,
1✔
3053
                )
1✔
3054

3055
        case req.GetRootHashOnly() != nil:
1✔
3056
                rootHash := req.GetRootHashOnly()
1✔
3057
                if len(rootHash) == 0 {
1✔
3058
                        return nil, fmt.Errorf("missing root hash")
×
3059
                }
×
3060

3061
                tapscript = input.TapscriptRootHashOnly(internalKey, rootHash)
1✔
3062

3063
        case req.GetFullKeyOnly():
1✔
3064
                tapscript = input.TapscriptFullKeyOnly(internalKey)
1✔
3065

3066
        default:
×
3067
                return nil, fmt.Errorf("invalid script")
×
3068
        }
3069

3070
        taprootScope := waddrmgr.KeyScopeBIP0086
1✔
3071
        addr, err := w.cfg.Wallet.ImportTaprootScript(taprootScope, tapscript)
1✔
3072
        if err != nil {
1✔
3073
                return nil, fmt.Errorf("error importing script into wallet: %w",
×
3074
                        err)
×
3075
        }
×
3076

3077
        return &ImportTapscriptResponse{
1✔
3078
                P2TrAddress: addr.Address().String(),
1✔
3079
        }, nil
1✔
3080
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc