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

lightningnetwork / lnd / 13186157113

06 Feb 2025 07:12PM UTC coverage: 58.806% (+9.5%) from 49.279%
13186157113

Pull #9470

github

ziggie1984
walletrpc+lncli: add new param. to bumpfee rpc.

Add new parameter deadline-delta to the bumpfee request and only
allow it to be used when the budget value is used as well.
Pull Request #9470: Make sure we fail the bump fee request as long as no budget is specified

19 of 39 new or added lines in 2 files covered. (48.72%)

316 existing lines in 4 files now uncovered.

136185 of 231582 relevant lines covered (58.81%)

19367.94 hits per line

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

66.09
/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
        "math"
14
        "os"
15
        "path/filepath"
16
        "sort"
17
        "time"
18

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

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

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

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

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

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

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

256
        cfg *Config
257
}
258

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

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

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

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

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

304
        walletKit := &WalletKit{
3✔
305
                cfg: cfg,
3✔
306
        }
3✔
307

3✔
308
        return walletKit, macPermissions, nil
3✔
309
}
310

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

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

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

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

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

3✔
346
        return nil
3✔
347
}
3✔
348

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

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

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

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

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

386
        r.WalletKitServer = subServer
3✔
387
        return subServer, macPermissions, nil
3✔
388
}
389

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

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

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

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

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

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

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

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

450
        return &ListUnspentResponse{
3✔
451
                Utxos: rpcUtxos,
3✔
452
        }, nil
3✔
453
}
454

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

553
        return &ListLeasesResponse{
×
554
                LockedUtxos: marshallLeases(leases),
×
555
        }, nil
×
556
}
557

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

654
        return lnrpc.RPCTransaction(res), nil
3✔
655
}
656

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

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

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

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

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

687
        return &PublishResponse{}, nil
3✔
688
}
689

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

918
        return &PendingSweepsResponse{
3✔
919
                PendingSweeps: rpcPendingSweeps,
3✔
920
        }, nil
3✔
921
}
922

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

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

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

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

950
        return &wire.OutPoint{
3✔
951
                Hash:  hash,
3✔
952
                Index: op.OutputIndex,
3✔
953
        }, nil
3✔
954
}
955

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

3✔
961
        // Get the specified fee rate if set.
3✔
962
        satPerKwOpt := fn.None[chainfee.SatPerKWeight]()
3✔
963

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

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

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

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

992
        var immediate bool
3✔
993
        switch {
3✔
NEW
994
        case in.Force && in.Immediate:
×
NEW
995
                return satPerKwOpt, false, fmt.Errorf("either Force or " +
×
NEW
996
                        "Immediate should be set, but not both")
×
997

NEW
998
        case in.Force:
×
NEW
999
                immediate = in.Force
×
1000

1001
        case in.Immediate:
3✔
1002
                immediate = in.Immediate
3✔
1003
        }
1004

1005
        if in.DeadlineDelta != 0 && in.Budget == 0 {
3✔
NEW
1006
                return satPerKwOpt, immediate, fmt.Errorf("budget must be " +
×
NEW
1007
                        "set if deadline-delta is set")
×
UNCOV
1008
        }
×
1009

1010
        return satPerKwOpt, immediate, nil
3✔
1011
}
1012

1013
// prepareSweepParams creates the sweep params to be used for the sweeper. It
1014
// returns the new params and a bool indicating whether this is an existing
1015
// input.
1016
func (w *WalletKit) prepareSweepParams(in *BumpFeeRequest,
1017
        op wire.OutPoint, currentHeight int32) (sweep.Params, bool, error) {
3✔
1018

3✔
1019
        // Return an error if the bump fee request is invalid.
3✔
1020
        feerate, immediate, err := validateBumpFeeRequest(in)
3✔
1021
        if err != nil {
3✔
NEW
1022
                return sweep.Params{}, false, err
×
NEW
1023
        }
×
1024

1025
        // In case the user specified a target conf, we estimate the fee rate
1026
        // for the given target on the fly.
1027
        if in.TargetConf != 0 {
5✔
1028
                startingFeeRate, err := w.cfg.FeeEstimator.EstimateFeePerKW(
2✔
1029
                        in.TargetConf,
2✔
1030
                )
2✔
1031
                if err != nil {
2✔
UNCOV
1032
                        return sweep.Params{}, false, fmt.Errorf("unable to "+
×
UNCOV
1033
                                "estimate fee rate for target conf %d: %w",
×
UNCOV
1034
                                in.TargetConf, err)
×
NEW
1035
                }
×
1036

1037
                // Set the starting fee rate to the estimated fee rate.
1038
                feerate = fn.Some(startingFeeRate)
2✔
1039
        }
1040

1041
        // Get the current pending inputs.
1042
        inputMap, err := w.cfg.Sweeper.PendingInputs()
3✔
1043
        if err != nil {
3✔
UNCOV
1044
                return sweep.Params{}, false, fmt.Errorf("unable to get "+
×
UNCOV
1045
                        "pending inputs: %w", err)
×
1046
        }
×
1047

1048
        // Find the pending input.
1049
        //
1050
        // TODO(yy): act differently based on the state of the input?
1051
        inp, ok := inputMap[op]
3✔
1052

3✔
1053
        if !ok {
5✔
1054
                // NOTE: if this input doesn't exist and the new budget is not
2✔
1055
                // specified, the params would have a zero budget.
2✔
1056
                params := sweep.Params{
2✔
1057
                        Immediate:       immediate,
2✔
1058
                        StartingFeeRate: feerate,
2✔
1059
                        Budget:          btcutil.Amount(in.Budget),
2✔
1060
                }
2✔
1061

2✔
1062
                return params, ok, nil
2✔
1063
        }
2✔
1064

1065
        // Find the existing budget used for this input. Note that this value
1066
        // must be greater than zero.
1067
        budget := inp.Params.Budget
3✔
1068

3✔
1069
        // Set the new budget if specified. If a new deadline delta is
3✔
1070
        // specified we also require the budget value which is checked in the
3✔
1071
        // validateBumpFeeRequest function.
3✔
1072
        if in.Budget != 0 {
6✔
1073
                budget = btcutil.Amount(in.Budget)
3✔
1074
        }
3✔
1075

1076
        // For an existing input, we assign it first, then overwrite it if
1077
        // a deadline is requested.
1078
        deadline := inp.Params.DeadlineHeight
3✔
1079

3✔
1080
        // Set the deadline if it was specified.
3✔
1081
        //
3✔
1082
        // TODO(yy): upgrade `falafel` so we can make this field optional. Atm
3✔
1083
        // we cannot distinguish between user's not setting the field and
3✔
1084
        // setting it to 0.
3✔
1085
        if in.DeadlineDelta != 0 {
6✔
1086
                deadline = fn.Some(int32(in.DeadlineDelta) + currentHeight)
3✔
1087
        }
3✔
1088

1089
        startingFeeRate := inp.Params.StartingFeeRate
3✔
1090
        // We only set the starting fee rate if it was specified else we keep
3✔
1091
        // the existing one.
3✔
1092
        if feerate.IsSome() {
5✔
1093
                startingFeeRate = feerate
2✔
1094
        }
2✔
1095

1096
        // Prepare the new sweep params.
1097
        //
1098
        // NOTE: if this input doesn't exist and the new budget is not
1099
        // specified, the params would have a zero budget.
1100
        params := sweep.Params{
3✔
1101
                Immediate:       immediate,
3✔
1102
                DeadlineHeight:  deadline,
3✔
1103
                StartingFeeRate: startingFeeRate,
3✔
1104
                Budget:          budget,
3✔
1105
        }
3✔
1106

3✔
1107
        log.Infof("[BumpFee]: bumping fee for existing input=%v, old "+
3✔
1108
                "params=%v, new params=%v", op, inp.Params, params)
3✔
1109

3✔
1110
        return params, ok, nil
3✔
1111
}
1112

1113
// BumpFee allows bumping the fee rate of an arbitrary input. A fee preference
1114
// can be expressed either as a specific fee rate or a delta of blocks in which
1115
// the output should be swept on-chain within. If a fee preference is not
1116
// explicitly specified, then an error is returned. The status of the input
1117
// sweep can be checked through the PendingSweeps RPC.
1118
func (w *WalletKit) BumpFee(ctx context.Context,
1119
        in *BumpFeeRequest) (*BumpFeeResponse, error) {
3✔
1120

3✔
1121
        // Parse the outpoint from the request.
3✔
1122
        op, err := UnmarshallOutPoint(in.Outpoint)
3✔
1123
        if err != nil {
3✔
UNCOV
1124
                return nil, err
×
UNCOV
1125
        }
×
1126

1127
        // Get the current height so we can calculate the deadline height.
1128
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
3✔
1129
        if err != nil {
3✔
UNCOV
1130
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
UNCOV
1131
                        err)
×
UNCOV
1132
        }
×
1133

1134
        // We now create a new sweeping params and update it in the sweeper.
1135
        // This will complicate the RBF conditions if this input has already
1136
        // been offered to sweeper before and it has already been included in a
1137
        // tx with other inputs. If this is the case, two results are possible:
1138
        // - either this input successfully RBFed the existing tx, or,
1139
        // - the budget of this input was not enough to RBF the existing tx.
1140
        params, existing, err := w.prepareSweepParams(in, *op, currentHeight)
3✔
1141
        if err != nil {
3✔
UNCOV
1142
                return nil, err
×
UNCOV
1143
        }
×
1144

1145
        // If this input exists, we will update its params.
1146
        if existing {
6✔
1147
                _, err = w.cfg.Sweeper.UpdateParams(*op, params)
3✔
1148
                if err != nil {
3✔
UNCOV
1149
                        return nil, err
×
UNCOV
1150
                }
×
1151

1152
                return &BumpFeeResponse{
3✔
1153
                        Status: "Successfully registered rbf-tx with sweeper",
3✔
1154
                }, nil
3✔
1155
        }
1156

1157
        // Otherwise, create a new sweeping request for this input.
1158
        err = w.sweepNewInput(op, uint32(currentHeight), params)
2✔
1159
        if err != nil {
2✔
UNCOV
1160
                return nil, err
×
UNCOV
1161
        }
×
1162

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

1168
// getWaitingCloseChannel returns the waiting close channel in case it does
1169
// exist in the underlying channel state database.
1170
func (w *WalletKit) getWaitingCloseChannel(
1171
        chanPoint wire.OutPoint) (*channeldb.OpenChannel, error) {
2✔
1172

2✔
1173
        // Fetch all channels, which still have their commitment transaction not
2✔
1174
        // confirmed (waiting close channels).
2✔
1175
        chans, err := w.cfg.ChanStateDB.FetchWaitingCloseChannels()
2✔
1176
        if err != nil {
2✔
UNCOV
1177
                return nil, err
×
UNCOV
1178
        }
×
1179

1180
        channel := fn.Find(chans, func(c *channeldb.OpenChannel) bool {
4✔
1181
                return c.FundingOutpoint == chanPoint
2✔
1182
        })
2✔
1183

1184
        return channel.UnwrapOrErr(errors.New("channel not found"))
2✔
1185
}
1186

1187
// BumpForceCloseFee bumps the fee rate of an unconfirmed anchor channel. It
1188
// updates the new fee rate parameters with the sweeper subsystem. Additionally
1189
// it will try to create anchor cpfp transactions for all possible commitment
1190
// transactions (local, remote, remote-dangling) so depending on which
1191
// commitment is in the local mempool only one of them will succeed in being
1192
// broadcasted.
1193
func (w *WalletKit) BumpForceCloseFee(_ context.Context,
1194
        in *BumpForceCloseFeeRequest) (*BumpForceCloseFeeResponse, error) {
2✔
1195

2✔
1196
        if in.ChanPoint == nil {
2✔
UNCOV
1197
                return nil, fmt.Errorf("no chan_point provided")
×
UNCOV
1198
        }
×
1199

1200
        lnrpcOutpoint, err := lnrpc.GetChannelOutPoint(in.ChanPoint)
2✔
1201
        if err != nil {
2✔
UNCOV
1202
                return nil, err
×
UNCOV
1203
        }
×
1204

1205
        outPoint, err := UnmarshallOutPoint(lnrpcOutpoint)
2✔
1206
        if err != nil {
2✔
1207
                return nil, err
×
UNCOV
1208
        }
×
1209

1210
        // Get the relevant channel if it is in the waiting close state.
1211
        channel, err := w.getWaitingCloseChannel(*outPoint)
2✔
1212
        if err != nil {
2✔
UNCOV
1213
                return nil, err
×
UNCOV
1214
        }
×
1215

1216
        if !channel.ChanType.HasAnchors() {
2✔
1217
                return nil, fmt.Errorf("not able to bump the fee of a " +
×
UNCOV
1218
                        "non-anchor channel")
×
UNCOV
1219
        }
×
1220

1221
        // Match pending sweeps with commitments of the channel for which a bump
1222
        // is requested. Depending on the commitment state when force closing
1223
        // the channel we might have up to 3 commitments to consider when
1224
        // bumping the fee.
1225
        commitSet := fn.NewSet[chainhash.Hash]()
2✔
1226

2✔
1227
        if channel.LocalCommitment.CommitTx != nil {
4✔
1228
                localTxID := channel.LocalCommitment.CommitTx.TxHash()
2✔
1229
                commitSet.Add(localTxID)
2✔
1230
        }
2✔
1231

1232
        if channel.RemoteCommitment.CommitTx != nil {
4✔
1233
                remoteTxID := channel.RemoteCommitment.CommitTx.TxHash()
2✔
1234
                commitSet.Add(remoteTxID)
2✔
1235
        }
2✔
1236

1237
        // Check whether there was a dangling commitment at the time the channel
1238
        // was force closed.
1239
        remoteCommitDiff, err := channel.RemoteCommitChainTip()
2✔
1240
        if err != nil && !errors.Is(err, channeldb.ErrNoPendingCommit) {
2✔
UNCOV
1241
                return nil, err
×
UNCOV
1242
        }
×
1243

1244
        if remoteCommitDiff != nil {
2✔
UNCOV
1245
                hash := remoteCommitDiff.Commitment.CommitTx.TxHash()
×
UNCOV
1246
                commitSet.Add(hash)
×
UNCOV
1247
        }
×
1248

1249
        // Retrieve all of the outputs the UtxoSweeper is currently trying to
1250
        // sweep.
1251
        inputsMap, err := w.cfg.Sweeper.PendingInputs()
2✔
1252
        if err != nil {
2✔
UNCOV
1253
                return nil, err
×
1254
        }
×
1255

1256
        // Get the current height so we can calculate the deadline height.
1257
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
2✔
1258
        if err != nil {
2✔
UNCOV
1259
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
UNCOV
1260
                        err)
×
UNCOV
1261
        }
×
1262

1263
        pendingSweeps := maps.Values(inputsMap)
2✔
1264

2✔
1265
        // Discard everything except for the anchor sweeps.
2✔
1266
        anchors := fn.Filter(
2✔
1267
                pendingSweeps,
2✔
1268
                func(sweep *sweep.PendingInputResponse) bool {
4✔
1269
                        // Only filter for anchor inputs because these are the
2✔
1270
                        // only inputs which can be used to bump a closed
2✔
1271
                        // unconfirmed commitment transaction.
2✔
1272
                        isCommitAnchor := sweep.WitnessType ==
2✔
1273
                                input.CommitmentAnchor
2✔
1274
                        isTaprootSweepSpend := sweep.WitnessType ==
2✔
1275
                                input.TaprootAnchorSweepSpend
2✔
1276
                        if !isCommitAnchor && !isTaprootSweepSpend {
2✔
UNCOV
1277
                                return false
×
UNCOV
1278
                        }
×
1279

1280
                        return commitSet.Contains(sweep.OutPoint.Hash)
2✔
1281
                },
1282
        )
1283

1284
        if len(anchors) == 0 {
2✔
UNCOV
1285
                return nil, fmt.Errorf("unable to find pending anchor outputs")
×
1286
        }
×
1287

1288
        // Filter all relevant anchor sweeps and update the sweep request.
1289
        for _, anchor := range anchors {
4✔
1290
                // Anchor cpfp bump request are predictable because they are
2✔
1291
                // swept separately hence not batched with other sweeps (they
2✔
1292
                // are marked with the exclusive group flag). Bumping the fee
2✔
1293
                // rate does not create any conflicting fee bump conditions.
2✔
1294
                // Either the rbf requirements are met or the bump is rejected
2✔
1295
                // by the mempool rules.
2✔
1296
                params, existing, err := w.prepareSweepParams(
2✔
1297
                        &BumpFeeRequest{
2✔
1298
                                Outpoint:    lnrpcOutpoint,
2✔
1299
                                TargetConf:  in.DeadlineDelta,
2✔
1300
                                SatPerVbyte: in.StartingFeerate,
2✔
1301
                                Immediate:   in.Immediate,
2✔
1302
                                Budget:      in.Budget,
2✔
1303
                        }, anchor.OutPoint, currentHeight,
2✔
1304
                )
2✔
1305
                if err != nil {
2✔
UNCOV
1306
                        return nil, err
×
UNCOV
1307
                }
×
1308

1309
                // There might be the case when an anchor sweep is confirmed
1310
                // between fetching the pending sweeps and preparing the sweep
1311
                // params. We log this case and proceed.
1312
                if !existing {
2✔
UNCOV
1313
                        log.Errorf("Sweep anchor input(%v) not known to the " +
×
UNCOV
1314
                                "sweeper subsystem")
×
1315
                        continue
×
1316
                }
1317

1318
                _, err = w.cfg.Sweeper.UpdateParams(anchor.OutPoint, params)
2✔
1319
                if err != nil {
2✔
UNCOV
1320
                        return nil, err
×
UNCOV
1321
                }
×
1322
        }
1323

1324
        return &BumpForceCloseFeeResponse{
2✔
1325
                Status: "Successfully registered anchor-cpfp transaction to" +
2✔
1326
                        "bump channel force close transaction",
2✔
1327
        }, nil
2✔
1328
}
1329

1330
// sweepNewInput handles the case where an input is seen the first time by the
1331
// sweeper. It will fetch the output from the wallet and construct an input and
1332
// offer it to the sweeper.
1333
//
1334
// NOTE: if the budget is not set, the default budget ratio is used.
1335
func (w *WalletKit) sweepNewInput(op *wire.OutPoint, currentHeight uint32,
1336
        params sweep.Params) error {
2✔
1337

2✔
1338
        log.Debugf("Attempting to sweep outpoint %s", op)
2✔
1339

2✔
1340
        // Since the sweeper is not aware of the input, we'll assume the user
2✔
1341
        // is attempting to bump an unconfirmed transaction's fee rate by
2✔
1342
        // sweeping an output within it under control of the wallet with a
2✔
1343
        // higher fee rate. In this case, this will be a CPFP.
2✔
1344
        //
2✔
1345
        // We'll gather all of the information required by the UtxoSweeper in
2✔
1346
        // order to sweep the output.
2✔
1347
        utxo, err := w.cfg.Wallet.FetchOutpointInfo(op)
2✔
1348
        if err != nil {
2✔
UNCOV
1349
                return err
×
UNCOV
1350
        }
×
1351

1352
        // We're only able to bump the fee of unconfirmed transactions.
1353
        if utxo.Confirmations > 0 {
2✔
UNCOV
1354
                return errors.New("unable to bump fee of a confirmed " +
×
UNCOV
1355
                        "transaction")
×
UNCOV
1356
        }
×
1357

1358
        // TODO(ziggie): This should only be set for CPFP requests. However
1359
        // this can lead to high fee rates in case the user specifies a
1360
        // deadline delta which is very low. So this should be revisited.
1361
        if params.Budget == 0 {
4✔
1362
                params.Budget = utxo.Value.MulF64(
2✔
1363
                        contractcourt.DefaultBudgetRatio,
2✔
1364
                )
2✔
1365
        }
2✔
1366

1367
        signDesc := &input.SignDescriptor{
2✔
1368
                Output: &wire.TxOut{
2✔
1369
                        PkScript: utxo.PkScript,
2✔
1370
                        Value:    int64(utxo.Value),
2✔
1371
                },
2✔
1372
                HashType: txscript.SigHashAll,
2✔
1373
        }
2✔
1374

2✔
1375
        var witnessType input.WitnessType
2✔
1376
        switch utxo.AddressType {
2✔
UNCOV
1377
        case lnwallet.WitnessPubKey:
×
UNCOV
1378
                witnessType = input.WitnessKeyHash
×
UNCOV
1379
        case lnwallet.NestedWitnessPubKey:
×
UNCOV
1380
                witnessType = input.NestedWitnessKeyHash
×
1381
        case lnwallet.TaprootPubkey:
2✔
1382
                witnessType = input.TaprootPubKeySpend
2✔
1383
                signDesc.HashType = txscript.SigHashDefault
2✔
UNCOV
1384
        default:
×
UNCOV
1385
                return fmt.Errorf("unknown input witness %v", op)
×
1386
        }
1387

1388
        log.Infof("[BumpFee]: bumping fee for new input=%v, params=%v", op,
2✔
1389
                params)
2✔
1390

2✔
1391
        inp := input.NewBaseInput(op, witnessType, signDesc, currentHeight)
2✔
1392
        if _, err = w.cfg.Sweeper.SweepInput(inp, params); err != nil {
2✔
1393
                return err
×
1394
        }
×
1395

1396
        return nil
2✔
1397
}
1398

1399
// ListSweeps returns a list of the sweeps that our node has published.
1400
func (w *WalletKit) ListSweeps(ctx context.Context,
1401
        in *ListSweepsRequest) (*ListSweepsResponse, error) {
3✔
1402

3✔
1403
        sweeps, err := w.cfg.Sweeper.ListSweeps()
3✔
1404
        if err != nil {
3✔
UNCOV
1405
                return nil, err
×
UNCOV
1406
        }
×
1407

1408
        sweepTxns := make(map[string]bool)
3✔
1409
        for _, sweep := range sweeps {
6✔
1410
                sweepTxns[sweep.String()] = true
3✔
1411
        }
3✔
1412

1413
        // Some of our sweeps could have been replaced by fee, or dropped out
1414
        // of the mempool. Here, we lookup our wallet transactions so that we
1415
        // can match our list of sweeps against the list of transactions that
1416
        // the wallet is still tracking. Sweeps are currently always swept to
1417
        // the default wallet account.
1418
        txns, firstIdx, lastIdx, err := w.cfg.Wallet.ListTransactionDetails(
3✔
1419
                in.StartHeight, btcwallet.UnconfirmedHeight,
3✔
1420
                lnwallet.DefaultAccountName, 0, 0,
3✔
1421
        )
3✔
1422
        if err != nil {
3✔
UNCOV
1423
                return nil, err
×
UNCOV
1424
        }
×
1425

1426
        var (
3✔
1427
                txids     []string
3✔
1428
                txDetails []*lnwallet.TransactionDetail
3✔
1429
        )
3✔
1430

3✔
1431
        for _, tx := range txns {
6✔
1432
                _, ok := sweepTxns[tx.Hash.String()]
3✔
1433
                if !ok {
6✔
1434
                        continue
3✔
1435
                }
1436

1437
                // Add the txid or full tx details depending on whether we want
1438
                // verbose output or not.
1439
                if in.Verbose {
6✔
1440
                        txDetails = append(txDetails, tx)
3✔
1441
                } else {
6✔
1442
                        txids = append(txids, tx.Hash.String())
3✔
1443
                }
3✔
1444
        }
1445

1446
        if in.Verbose {
6✔
1447
                return &ListSweepsResponse{
3✔
1448
                        Sweeps: &ListSweepsResponse_TransactionDetails{
3✔
1449
                                TransactionDetails: lnrpc.RPCTransactionDetails(
3✔
1450
                                        txDetails, firstIdx, lastIdx,
3✔
1451
                                ),
3✔
1452
                        },
3✔
1453
                }, nil
3✔
1454
        }
3✔
1455

1456
        return &ListSweepsResponse{
3✔
1457
                Sweeps: &ListSweepsResponse_TransactionIds{
3✔
1458
                        TransactionIds: &ListSweepsResponse_TransactionIDs{
3✔
1459
                                TransactionIds: txids,
3✔
1460
                        },
3✔
1461
                },
3✔
1462
        }, nil
3✔
1463
}
1464

1465
// LabelTransaction adds a label to a transaction.
1466
func (w *WalletKit) LabelTransaction(ctx context.Context,
1467
        req *LabelTransactionRequest) (*LabelTransactionResponse, error) {
3✔
1468

3✔
1469
        // Check that the label provided in non-zero.
3✔
1470
        if len(req.Label) == 0 {
6✔
1471
                return nil, ErrZeroLabel
3✔
1472
        }
3✔
1473

1474
        // Validate the length of the non-zero label. We do not need to use the
1475
        // label returned here, because the original is non-zero so will not
1476
        // be replaced.
1477
        if _, err := labels.ValidateAPI(req.Label); err != nil {
3✔
UNCOV
1478
                return nil, err
×
UNCOV
1479
        }
×
1480

1481
        hash, err := chainhash.NewHash(req.Txid)
3✔
1482
        if err != nil {
3✔
UNCOV
1483
                return nil, err
×
UNCOV
1484
        }
×
1485

1486
        err = w.cfg.Wallet.LabelTransaction(*hash, req.Label, req.Overwrite)
3✔
1487

3✔
1488
        return &LabelTransactionResponse{
3✔
1489
                Status: fmt.Sprintf("transaction label '%s' added", req.Label),
3✔
1490
        }, err
3✔
1491
}
1492

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

3✔
1526
        coinSelectionStrategy, err := lnrpc.UnmarshallCoinSelectionStrategy(
3✔
1527
                req.CoinSelectionStrategy, w.cfg.CoinSelectionStrategy,
3✔
1528
        )
3✔
1529
        if err != nil {
3✔
UNCOV
1530
                return nil, err
×
UNCOV
1531
        }
×
1532

1533
        // Determine the desired transaction fee.
1534
        var feeSatPerKW chainfee.SatPerKWeight
3✔
1535
        switch {
3✔
1536
        // Estimate the fee by the target number of blocks to confirmation.
UNCOV
1537
        case req.GetTargetConf() != 0:
×
UNCOV
1538
                targetConf := req.GetTargetConf()
×
1539
                if targetConf < 2 {
×
1540
                        return nil, fmt.Errorf("confirmation target must be " +
×
UNCOV
1541
                                "greater than 1")
×
UNCOV
1542
                }
×
1543

UNCOV
1544
                feeSatPerKW, err = w.cfg.FeeEstimator.EstimateFeePerKW(
×
UNCOV
1545
                        targetConf,
×
1546
                )
×
1547
                if err != nil {
×
1548
                        return nil, fmt.Errorf("could not estimate fee: %w",
×
1549
                                err)
×
1550
                }
×
1551

1552
        // Convert the fee to sat/kW from the specified sat/vByte.
1553
        case req.GetSatPerVbyte() != 0:
3✔
1554
                feeSatPerKW = chainfee.SatPerKVByte(
3✔
1555
                        req.GetSatPerVbyte() * 1000,
3✔
1556
                ).FeePerKWeight()
3✔
1557

1558
        case req.GetSatPerKw() != 0:
×
1559
                feeSatPerKW = chainfee.SatPerKWeight(req.GetSatPerKw())
×
1560

UNCOV
1561
        default:
×
UNCOV
1562
                return nil, fmt.Errorf("fee definition missing, need to " +
×
UNCOV
1563
                        "specify either target_conf, sat_per_vbyte or " +
×
UNCOV
1564
                        "sat_per_kw")
×
1565
        }
1566

1567
        // Then, we'll extract the minimum number of confirmations that each
1568
        // output we use to fund the transaction should satisfy.
1569
        minConfs, err := lnrpc.ExtractMinConfs(
3✔
1570
                req.GetMinConfs(), req.GetSpendUnconfirmed(),
3✔
1571
        )
3✔
1572
        if err != nil {
3✔
1573
                return nil, err
×
UNCOV
1574
        }
×
1575

1576
        // We'll assume the PSBT will be funded by the default account unless
1577
        // otherwise specified.
1578
        account := lnwallet.DefaultAccountName
3✔
1579
        if req.Account != "" {
6✔
1580
                account = req.Account
3✔
1581
        }
3✔
1582

1583
        // There are three ways a user can specify what we call the template (a
1584
        // list of inputs and outputs to use in the PSBT): Either as a PSBT
1585
        // packet directly with no coin selection, a PSBT with coin selection or
1586
        // as a special RPC message. Find out which one the user wants to use,
1587
        // they are mutually exclusive.
1588
        switch {
3✔
1589
        // The template is specified as a PSBT. All we have to do is parse it.
1590
        case req.GetPsbt() != nil:
3✔
1591
                r := bytes.NewReader(req.GetPsbt())
3✔
1592
                packet, err := psbt.NewFromRawBytes(r, false)
3✔
1593
                if err != nil {
3✔
UNCOV
1594
                        return nil, fmt.Errorf("could not parse PSBT: %w", err)
×
UNCOV
1595
                }
×
1596

1597
                // Run the actual funding process now, using the internal
1598
                // wallet.
1599
                return w.fundPsbtInternalWallet(
3✔
1600
                        account, keyScopeFromChangeAddressType(req.ChangeType),
3✔
1601
                        packet, minConfs, feeSatPerKW, coinSelectionStrategy,
3✔
1602
                )
3✔
1603

1604
        // The template is specified as a PSBT with the intention to perform
1605
        // coin selection even if inputs are already present.
1606
        case req.GetCoinSelect() != nil:
3✔
1607
                coinSelectRequest := req.GetCoinSelect()
3✔
1608
                r := bytes.NewReader(coinSelectRequest.Psbt)
3✔
1609
                packet, err := psbt.NewFromRawBytes(r, false)
3✔
1610
                if err != nil {
3✔
UNCOV
1611
                        return nil, fmt.Errorf("could not parse PSBT: %w", err)
×
UNCOV
1612
                }
×
1613

1614
                numOutputs := int32(len(packet.UnsignedTx.TxOut))
3✔
1615
                if numOutputs == 0 {
3✔
UNCOV
1616
                        return nil, fmt.Errorf("no outputs specified in " +
×
UNCOV
1617
                                "template")
×
UNCOV
1618
                }
×
1619

1620
                outputSum := int64(0)
3✔
1621
                for _, txOut := range packet.UnsignedTx.TxOut {
6✔
1622
                        outputSum += txOut.Value
3✔
1623
                }
3✔
1624
                if outputSum <= 0 {
3✔
1625
                        return nil, fmt.Errorf("output sum must be positive")
×
1626
                }
×
1627

1628
                var (
3✔
1629
                        changeIndex int32 = -1
3✔
1630
                        changeType  chanfunding.ChangeAddressType
3✔
1631
                )
3✔
1632
                switch t := coinSelectRequest.ChangeOutput.(type) {
3✔
1633
                // The user wants to use an existing output as change output.
1634
                case *PsbtCoinSelect_ExistingOutputIndex:
3✔
1635
                        if t.ExistingOutputIndex < 0 ||
3✔
1636
                                t.ExistingOutputIndex >= numOutputs {
3✔
UNCOV
1637

×
UNCOV
1638
                                return nil, fmt.Errorf("change output index "+
×
UNCOV
1639
                                        "out of range: %d",
×
UNCOV
1640
                                        t.ExistingOutputIndex)
×
UNCOV
1641
                        }
×
1642

1643
                        changeIndex = t.ExistingOutputIndex
3✔
1644

3✔
1645
                        changeOut := packet.UnsignedTx.TxOut[changeIndex]
3✔
1646
                        _, err := txscript.ParsePkScript(changeOut.PkScript)
3✔
1647
                        if err != nil {
3✔
1648
                                return nil, fmt.Errorf("error parsing change "+
×
1649
                                        "script: %w", err)
×
1650
                        }
×
1651

1652
                        changeType = chanfunding.ExistingChangeAddress
3✔
1653

1654
                // The user wants to use a new output as change output.
UNCOV
1655
                case *PsbtCoinSelect_Add:
×
UNCOV
1656
                        // We already set the change index to -1 above to
×
1657
                        // indicate no change output should be used if possible
×
1658
                        // or a new one should be created if needed. So we only
×
1659
                        // need to parse the type of change output we want to
×
UNCOV
1660
                        // create.
×
UNCOV
1661
                        switch req.ChangeType {
×
UNCOV
1662
                        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
×
UNCOV
1663
                                changeType = chanfunding.P2TRChangeAddress
×
1664

1665
                        default:
×
1666
                                changeType = chanfunding.P2WKHChangeAddress
×
1667
                        }
1668

1669
                default:
×
1670
                        return nil, fmt.Errorf("unknown change output type")
×
1671
                }
1672

1673
                maxFeeRatio := chanfunding.DefaultMaxFeeRatio
3✔
1674

3✔
1675
                if req.MaxFeeRatio != 0 {
3✔
UNCOV
1676
                        maxFeeRatio = req.MaxFeeRatio
×
UNCOV
1677
                }
×
1678

1679
                // Run the actual funding process now, using the channel funding
1680
                // coin selection algorithm.
1681
                return w.fundPsbtCoinSelect(
3✔
1682
                        account, changeIndex, packet, minConfs, changeType,
3✔
1683
                        feeSatPerKW, coinSelectionStrategy, maxFeeRatio,
3✔
1684
                )
3✔
1685

1686
        // The template is specified as a RPC message. We need to create a new
1687
        // PSBT and copy the RPC information over.
1688
        case req.GetRaw() != nil:
3✔
1689
                tpl := req.GetRaw()
3✔
1690

3✔
1691
                txOut := make([]*wire.TxOut, 0, len(tpl.Outputs))
3✔
1692
                for addrStr, amt := range tpl.Outputs {
6✔
1693
                        addr, err := btcutil.DecodeAddress(
3✔
1694
                                addrStr, w.cfg.ChainParams,
3✔
1695
                        )
3✔
1696
                        if err != nil {
3✔
UNCOV
1697
                                return nil, fmt.Errorf("error parsing address "+
×
UNCOV
1698
                                        "%s for network %s: %v", addrStr,
×
UNCOV
1699
                                        w.cfg.ChainParams.Name, err)
×
UNCOV
1700
                        }
×
1701

1702
                        if !addr.IsForNet(w.cfg.ChainParams) {
3✔
UNCOV
1703
                                return nil, fmt.Errorf("address is not for %s",
×
UNCOV
1704
                                        w.cfg.ChainParams.Name)
×
UNCOV
1705
                        }
×
1706

1707
                        pkScript, err := txscript.PayToAddrScript(addr)
3✔
1708
                        if err != nil {
3✔
1709
                                return nil, fmt.Errorf("error getting pk "+
×
UNCOV
1710
                                        "script for address %s: %w", addrStr,
×
UNCOV
1711
                                        err)
×
1712
                        }
×
1713

1714
                        txOut = append(txOut, &wire.TxOut{
3✔
1715
                                Value:    int64(amt),
3✔
1716
                                PkScript: pkScript,
3✔
1717
                        })
3✔
1718
                }
1719

1720
                txIn := make([]*wire.OutPoint, len(tpl.Inputs))
3✔
1721
                for idx, in := range tpl.Inputs {
3✔
UNCOV
1722
                        op, err := UnmarshallOutPoint(in)
×
UNCOV
1723
                        if err != nil {
×
UNCOV
1724
                                return nil, fmt.Errorf("error parsing "+
×
UNCOV
1725
                                        "outpoint: %w", err)
×
UNCOV
1726
                        }
×
UNCOV
1727
                        txIn[idx] = op
×
1728
                }
1729

1730
                sequences := make([]uint32, len(txIn))
3✔
1731
                packet, err := psbt.New(txIn, txOut, 2, 0, sequences)
3✔
1732
                if err != nil {
3✔
1733
                        return nil, fmt.Errorf("could not create PSBT: %w", err)
×
1734
                }
×
1735

1736
                // Run the actual funding process now, using the internal
1737
                // wallet.
1738
                return w.fundPsbtInternalWallet(
3✔
1739
                        account, keyScopeFromChangeAddressType(req.ChangeType),
3✔
1740
                        packet, minConfs, feeSatPerKW, coinSelectionStrategy,
3✔
1741
                )
3✔
1742

1743
        default:
×
UNCOV
1744
                return nil, fmt.Errorf("transaction template missing, need " +
×
UNCOV
1745
                        "to specify either PSBT or raw TX template")
×
1746
        }
1747
}
1748

1749
// fundPsbtInternalWallet uses the "old" PSBT funding method of the internal
1750
// wallet that does not allow specifying custom inputs while selecting coins.
1751
func (w *WalletKit) fundPsbtInternalWallet(account string,
1752
        keyScope *waddrmgr.KeyScope, packet *psbt.Packet, minConfs int32,
1753
        feeSatPerKW chainfee.SatPerKWeight,
1754
        strategy base.CoinSelectionStrategy) (*FundPsbtResponse, error) {
3✔
1755

3✔
1756
        // The RPC parsing part is now over. Several of the following operations
3✔
1757
        // require us to hold the global coin selection lock, so we do the rest
3✔
1758
        // of the tasks while holding the lock. The result is a list of locked
3✔
1759
        // UTXOs.
3✔
1760
        var response *FundPsbtResponse
3✔
1761
        err := w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
6✔
1762
                // In case the user did specify inputs, we need to make sure
3✔
1763
                // they are known to us, still unspent and not yet locked.
3✔
1764
                if len(packet.UnsignedTx.TxIn) > 0 {
6✔
1765
                        // Get a list of all unspent witness outputs.
3✔
1766
                        utxos, err := w.cfg.Wallet.ListUnspentWitness(
3✔
1767
                                minConfs, defaultMaxConf, account,
3✔
1768
                        )
3✔
1769
                        if err != nil {
3✔
UNCOV
1770
                                return err
×
UNCOV
1771
                        }
×
1772

1773
                        // filterFn makes sure utxos which are unconfirmed and
1774
                        // still used by the sweeper are not used.
1775
                        filterFn := func(u *lnwallet.Utxo) bool {
6✔
1776
                                // Confirmed utxos are always allowed.
3✔
1777
                                if u.Confirmations > 0 {
6✔
1778
                                        return true
3✔
1779
                                }
3✔
1780

1781
                                // Unconfirmed utxos in use by the sweeper are
1782
                                // not stable to use because they can be
1783
                                // replaced.
1784
                                if w.cfg.Sweeper.IsSweeperOutpoint(u.OutPoint) {
6✔
1785
                                        log.Warnf("Cannot use unconfirmed "+
3✔
1786
                                                "utxo=%v because it is "+
3✔
1787
                                                "unstable and could be "+
3✔
1788
                                                "replaced", u.OutPoint)
3✔
1789

3✔
1790
                                        return false
3✔
1791
                                }
3✔
1792

UNCOV
1793
                                return true
×
1794
                        }
1795

1796
                        eligibleUtxos := fn.Filter(utxos, filterFn)
3✔
1797

3✔
1798
                        // Validate all inputs against our known list of UTXOs
3✔
1799
                        // now.
3✔
1800
                        err = verifyInputsUnspent(
3✔
1801
                                packet.UnsignedTx.TxIn, eligibleUtxos,
3✔
1802
                        )
3✔
1803
                        if err != nil {
6✔
1804
                                return err
3✔
1805
                        }
3✔
1806
                }
1807

1808
                // currentHeight is needed to determine whether the internal
1809
                // wallet utxo is still unconfirmed.
1810
                _, currentHeight, err := w.cfg.Chain.GetBestBlock()
3✔
1811
                if err != nil {
3✔
UNCOV
1812
                        return fmt.Errorf("unable to retrieve current "+
×
UNCOV
1813
                                "height: %v", err)
×
UNCOV
1814
                }
×
1815

1816
                // restrictUnstableUtxos is a filter function which disallows
1817
                // the usage of unconfirmed outputs published (still in use) by
1818
                // the sweeper.
1819
                restrictUnstableUtxos := func(utxo wtxmgr.Credit) bool {
6✔
1820
                        // Wallet utxos which are unmined have a height
3✔
1821
                        // of -1.
3✔
1822
                        if utxo.Height != -1 && utxo.Height <= currentHeight {
6✔
1823
                                // Confirmed utxos are always allowed.
3✔
1824
                                return true
3✔
1825
                        }
3✔
1826

1827
                        // Utxos used by the sweeper are not used for
1828
                        // channel openings.
1829
                        allowed := !w.cfg.Sweeper.IsSweeperOutpoint(
3✔
1830
                                utxo.OutPoint,
3✔
1831
                        )
3✔
1832
                        if !allowed {
6✔
1833
                                log.Warnf("Cannot use unconfirmed "+
3✔
1834
                                        "utxo=%v because it is "+
3✔
1835
                                        "unstable and could be "+
3✔
1836
                                        "replaced", utxo.OutPoint)
3✔
1837
                        }
3✔
1838

1839
                        return allowed
3✔
1840
                }
1841

1842
                // We made sure the input from the user is as sane as possible.
1843
                // We can now ask the wallet to fund the TX. This will not yet
1844
                // lock any coins but might still change the wallet DB by
1845
                // generating a new change address.
1846
                changeIndex, err := w.cfg.Wallet.FundPsbt(
3✔
1847
                        packet, minConfs, feeSatPerKW, account, keyScope,
3✔
1848
                        strategy, restrictUnstableUtxos,
3✔
1849
                )
3✔
1850
                if err != nil {
6✔
1851
                        return fmt.Errorf("wallet couldn't fund PSBT: %w", err)
3✔
1852
                }
3✔
1853

1854
                // Now we have obtained a set of coins that can be used to fund
1855
                // the TX. Let's lock them to be sure they aren't spent by the
1856
                // time the PSBT is published. This is the action we do here
1857
                // that could cause an error. Therefore, if some of the UTXOs
1858
                // cannot be locked, the rollback of the other's locks also
1859
                // happens in this function. If we ever need to do more after
1860
                // this function, we need to extract the rollback needs to be
1861
                // extracted into a defer.
1862
                outpoints := make([]wire.OutPoint, len(packet.UnsignedTx.TxIn))
3✔
1863
                for i, txIn := range packet.UnsignedTx.TxIn {
6✔
1864
                        outpoints[i] = txIn.PreviousOutPoint
3✔
1865
                }
3✔
1866

1867
                response, err = w.lockAndCreateFundingResponse(
3✔
1868
                        packet, outpoints, changeIndex,
3✔
1869
                )
3✔
1870

3✔
1871
                return err
3✔
1872
        })
1873
        if err != nil {
6✔
1874
                return nil, err
3✔
1875
        }
3✔
1876

1877
        return response, nil
3✔
1878
}
1879

1880
// fundPsbtCoinSelect uses the "new" PSBT funding method using the channel
1881
// funding coin selection algorithm that allows specifying custom inputs while
1882
// selecting coins.
1883
func (w *WalletKit) fundPsbtCoinSelect(account string, changeIndex int32,
1884
        packet *psbt.Packet, minConfs int32,
1885
        changeType chanfunding.ChangeAddressType,
1886
        feeRate chainfee.SatPerKWeight, strategy base.CoinSelectionStrategy,
1887
        maxFeeRatio float64) (*FundPsbtResponse, error) {
3✔
1888

3✔
1889
        // We want to make sure we don't select any inputs that are already
3✔
1890
        // specified in the template. To do that, we require those inputs to
3✔
1891
        // either not belong to this lnd at all or to be already locked through
3✔
1892
        // a manual lock call by the user. Either way, they should not appear in
3✔
1893
        // the list of unspent outputs.
3✔
1894
        err := w.assertNotAvailable(packet.UnsignedTx.TxIn, minConfs, account)
3✔
1895
        if err != nil {
3✔
UNCOV
1896
                return nil, err
×
UNCOV
1897
        }
×
1898

1899
        // In case the user just specified the input outpoints of UTXOs we own,
1900
        // the fee estimation below will error out because the UTXO information
1901
        // is missing. We need to fetch the UTXO information from the wallet
1902
        // and add it to the PSBT. We ignore inputs we don't actually know as
1903
        // they could belong to another wallet.
1904
        err = w.cfg.Wallet.DecorateInputs(packet, false)
3✔
1905
        if err != nil {
3✔
1906
                return nil, fmt.Errorf("error decorating inputs: %w", err)
×
UNCOV
1907
        }
×
1908

1909
        // Before we select anything, we need to calculate the input, output and
1910
        // current weight amounts. While doing that we also ensure the PSBT has
1911
        // all the required information we require at this step.
1912
        var (
3✔
1913
                inputSum, outputSum btcutil.Amount
3✔
1914
                estimator           input.TxWeightEstimator
3✔
1915
        )
3✔
1916
        for i := range packet.Inputs {
6✔
1917
                in := packet.Inputs[i]
3✔
1918

3✔
1919
                err := btcwallet.EstimateInputWeight(&in, &estimator)
3✔
1920
                if err != nil {
3✔
UNCOV
1921
                        return nil, fmt.Errorf("error estimating input "+
×
UNCOV
1922
                                "weight: %w", err)
×
UNCOV
1923
                }
×
1924

1925
                inputSum += btcutil.Amount(in.WitnessUtxo.Value)
3✔
1926
        }
1927
        for i := range packet.UnsignedTx.TxOut {
6✔
1928
                out := packet.UnsignedTx.TxOut[i]
3✔
1929

3✔
1930
                estimator.AddOutput(out.PkScript)
3✔
1931
                outputSum += btcutil.Amount(out.Value)
3✔
1932
        }
3✔
1933

1934
        // The amount we want to fund is the total output sum plus the current
1935
        // fee estimate, minus the sum of any already specified inputs. Since we
1936
        // pass the estimator of the current transaction into the coin selection
1937
        // algorithm, we don't need to subtract the fees here.
1938
        fundingAmount := outputSum - inputSum
3✔
1939

3✔
1940
        var changeDustLimit btcutil.Amount
3✔
1941
        switch changeType {
3✔
UNCOV
1942
        case chanfunding.P2TRChangeAddress:
×
UNCOV
1943
                changeDustLimit = lnwallet.DustLimitForSize(input.P2TRSize)
×
1944

UNCOV
1945
        case chanfunding.P2WKHChangeAddress:
×
UNCOV
1946
                changeDustLimit = lnwallet.DustLimitForSize(input.P2WPKHSize)
×
1947

1948
        case chanfunding.ExistingChangeAddress:
3✔
1949
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
3✔
1950
                changeDustLimit = lnwallet.DustLimitForSize(
3✔
1951
                        len(changeOut.PkScript),
3✔
1952
                )
3✔
1953
        }
1954

1955
        // Do we already have enough inputs specified to pay for the TX as it
1956
        // is? In that case we only need to allocate any change, if there is
1957
        // any.
1958
        packetFeeNoChange := feeRate.FeeForWeight(estimator.Weight())
3✔
1959
        if inputSum >= outputSum+packetFeeNoChange {
3✔
UNCOV
1960
                // Calculate the packet's fee with a change output so, so we can
×
UNCOV
1961
                // let the coin selection algorithm decide whether to use a
×
UNCOV
1962
                // change output or not.
×
UNCOV
1963
                switch changeType {
×
UNCOV
1964
                case chanfunding.P2TRChangeAddress:
×
UNCOV
1965
                        estimator.AddP2TROutput()
×
1966

UNCOV
1967
                case chanfunding.P2WKHChangeAddress:
×
UNCOV
1968
                        estimator.AddP2WKHOutput()
×
1969
                }
1970
                packetFeeWithChange := feeRate.FeeForWeight(estimator.Weight())
×
1971

×
1972
                changeAmt, needMore, err := chanfunding.CalculateChangeAmount(
×
1973
                        inputSum, outputSum, packetFeeNoChange,
×
1974
                        packetFeeWithChange, changeDustLimit, changeType,
×
UNCOV
1975
                        maxFeeRatio,
×
1976
                )
×
1977
                if err != nil {
×
UNCOV
1978
                        return nil, fmt.Errorf("error calculating change "+
×
1979
                                "amount: %w", err)
×
1980
                }
×
1981

1982
                // We shouldn't get into this branch if the input sum isn't
1983
                // enough to pay for the current package without a change
1984
                // output. So this should never be non-zero.
1985
                if needMore != 0 {
×
1986
                        return nil, fmt.Errorf("internal error with change " +
×
1987
                                "amount calculation")
×
1988
                }
×
1989

UNCOV
1990
                if changeAmt > 0 {
×
UNCOV
1991
                        changeIndex, err = w.handleChange(
×
UNCOV
1992
                                packet, changeIndex, int64(changeAmt),
×
UNCOV
1993
                                changeType, account,
×
1994
                        )
×
1995
                        if err != nil {
×
1996
                                return nil, fmt.Errorf("error handling change "+
×
1997
                                        "amount: %w", err)
×
UNCOV
1998
                        }
×
1999
                }
2000

2001
                // We're done. Let's serialize and return the updated package.
2002
                return w.lockAndCreateFundingResponse(packet, nil, changeIndex)
×
2003
        }
2004

2005
        // The RPC parsing part is now over. Several of the following operations
2006
        // require us to hold the global coin selection lock, so we do the rest
2007
        // of the tasks while holding the lock. The result is a list of locked
2008
        // UTXOs.
2009
        var response *FundPsbtResponse
3✔
2010
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
6✔
2011
                // Get a list of all unspent witness outputs.
3✔
2012
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
3✔
2013
                        minConfs, defaultMaxConf, account,
3✔
2014
                )
3✔
2015
                if err != nil {
3✔
UNCOV
2016
                        return err
×
UNCOV
2017
                }
×
2018

2019
                coins := make([]base.Coin, len(utxos))
3✔
2020
                for i, utxo := range utxos {
6✔
2021
                        coins[i] = base.Coin{
3✔
2022
                                TxOut: wire.TxOut{
3✔
2023
                                        Value:    int64(utxo.Value),
3✔
2024
                                        PkScript: utxo.PkScript,
3✔
2025
                                },
3✔
2026
                                OutPoint: utxo.OutPoint,
3✔
2027
                        }
3✔
2028
                }
3✔
2029

2030
                selectedCoins, changeAmount, err := chanfunding.CoinSelect(
3✔
2031
                        feeRate, fundingAmount, changeDustLimit, coins,
3✔
2032
                        strategy, estimator, changeType, maxFeeRatio,
3✔
2033
                )
3✔
2034
                if err != nil {
3✔
UNCOV
2035
                        return fmt.Errorf("error selecting coins: %w", err)
×
UNCOV
2036
                }
×
2037

2038
                if changeAmount > 0 {
6✔
2039
                        changeIndex, err = w.handleChange(
3✔
2040
                                packet, changeIndex, int64(changeAmount),
3✔
2041
                                changeType, account,
3✔
2042
                        )
3✔
2043
                        if err != nil {
3✔
2044
                                return fmt.Errorf("error handling change "+
×
2045
                                        "amount: %w", err)
×
UNCOV
2046
                        }
×
2047
                }
2048

2049
                addedOutpoints := make([]wire.OutPoint, len(selectedCoins))
3✔
2050
                for i := range selectedCoins {
6✔
2051
                        coin := selectedCoins[i]
3✔
2052
                        addedOutpoints[i] = coin.OutPoint
3✔
2053

3✔
2054
                        packet.UnsignedTx.TxIn = append(
3✔
2055
                                packet.UnsignedTx.TxIn, &wire.TxIn{
3✔
2056
                                        PreviousOutPoint: coin.OutPoint,
3✔
2057
                                },
3✔
2058
                        )
3✔
2059
                        packet.Inputs = append(packet.Inputs, psbt.PInput{
3✔
2060
                                WitnessUtxo: &coin.TxOut,
3✔
2061
                        })
3✔
2062
                }
3✔
2063

2064
                // Now that we've added the bare TX inputs, we also need to add
2065
                // the more verbose input information to the packet, so a future
2066
                // signer doesn't need to do any lookups. We skip any inputs
2067
                // that our wallet doesn't own.
2068
                err = w.cfg.Wallet.DecorateInputs(packet, false)
3✔
2069
                if err != nil {
3✔
UNCOV
2070
                        return fmt.Errorf("error decorating inputs: %w", err)
×
UNCOV
2071
                }
×
2072

2073
                response, err = w.lockAndCreateFundingResponse(
3✔
2074
                        packet, addedOutpoints, changeIndex,
3✔
2075
                )
3✔
2076

3✔
2077
                return err
3✔
2078
        })
2079
        if err != nil {
3✔
2080
                return nil, err
×
UNCOV
2081
        }
×
2082

2083
        return response, nil
3✔
2084
}
2085

2086
// assertNotAvailable makes sure the specified inputs either don't belong to
2087
// this node or are already locked by the user.
2088
func (w *WalletKit) assertNotAvailable(inputs []*wire.TxIn, minConfs int32,
2089
        account string) error {
3✔
2090

3✔
2091
        return w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
6✔
2092
                // Get a list of all unspent witness outputs.
3✔
2093
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
3✔
2094
                        minConfs, defaultMaxConf, account,
3✔
2095
                )
3✔
2096
                if err != nil {
3✔
UNCOV
2097
                        return fmt.Errorf("error fetching UTXOs: %w", err)
×
UNCOV
2098
                }
×
2099

2100
                // We'll now check that none of the inputs specified in the
2101
                // template are available to us. That means they either don't
2102
                // belong to us or are already locked by the user.
2103
                for _, txIn := range inputs {
6✔
2104
                        for _, utxo := range utxos {
6✔
2105
                                if txIn.PreviousOutPoint == utxo.OutPoint {
3✔
2106
                                        return fmt.Errorf("input %v is not "+
×
2107
                                                "locked", txIn.PreviousOutPoint)
×
UNCOV
2108
                                }
×
2109
                        }
2110
                }
2111

2112
                return nil
3✔
2113
        })
2114
}
2115

2116
// lockAndCreateFundingResponse locks the given outpoints and creates a funding
2117
// response with the serialized PSBT, the change index and the locked UTXOs.
2118
func (w *WalletKit) lockAndCreateFundingResponse(packet *psbt.Packet,
2119
        newOutpoints []wire.OutPoint, changeIndex int32) (*FundPsbtResponse,
2120
        error) {
3✔
2121

3✔
2122
        // Make sure we can properly serialize the packet. If this goes wrong
3✔
2123
        // then something isn't right with the inputs, and we probably shouldn't
3✔
2124
        // try to lock any of them.
3✔
2125
        var buf bytes.Buffer
3✔
2126
        err := packet.Serialize(&buf)
3✔
2127
        if err != nil {
3✔
UNCOV
2128
                return nil, fmt.Errorf("error serializing funded PSBT: %w", err)
×
UNCOV
2129
        }
×
2130

2131
        locks, err := lockInputs(w.cfg.Wallet, newOutpoints)
3✔
2132
        if err != nil {
3✔
UNCOV
2133
                return nil, fmt.Errorf("could not lock inputs: %w", err)
×
UNCOV
2134
        }
×
2135

2136
        // Convert the lock leases to the RPC format.
2137
        rpcLocks := marshallLeases(locks)
3✔
2138

3✔
2139
        return &FundPsbtResponse{
3✔
2140
                FundedPsbt:        buf.Bytes(),
3✔
2141
                ChangeOutputIndex: changeIndex,
3✔
2142
                LockedUtxos:       rpcLocks,
3✔
2143
        }, nil
3✔
2144
}
2145

2146
// handleChange is a closure that either adds the non-zero change amount to an
2147
// existing output or creates a change output. The function returns the new
2148
// change output index if a new change output was added.
2149
func (w *WalletKit) handleChange(packet *psbt.Packet, changeIndex int32,
2150
        changeAmount int64, changeType chanfunding.ChangeAddressType,
2151
        changeAccount string) (int32, error) {
3✔
2152

3✔
2153
        // Does an existing output get the change?
3✔
2154
        if changeIndex >= 0 {
6✔
2155
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
3✔
2156
                changeOut.Value += changeAmount
3✔
2157

3✔
2158
                return changeIndex, nil
3✔
2159
        }
3✔
2160

2161
        // The user requested a new change output.
UNCOV
2162
        addrType := addrTypeFromChangeAddressType(changeType)
×
UNCOV
2163
        changeAddr, err := w.cfg.Wallet.NewAddress(
×
UNCOV
2164
                addrType, true, changeAccount,
×
UNCOV
2165
        )
×
UNCOV
2166
        if err != nil {
×
UNCOV
2167
                return 0, fmt.Errorf("could not derive change address: %w", err)
×
UNCOV
2168
        }
×
2169

UNCOV
2170
        changeScript, err := txscript.PayToAddrScript(changeAddr)
×
2171
        if err != nil {
×
2172
                return 0, fmt.Errorf("could not derive change script: %w", err)
×
2173
        }
×
2174

2175
        // We need to add the derivation info for the change address in case it
2176
        // is a P2TR address. This is mostly to prove it's a bare BIP-0086
2177
        // address, which is required for some protocols (such as Taproot
2178
        // Assets).
2179
        pOut := psbt.POutput{}
×
2180
        _, isTaprootChangeAddr := changeAddr.(*btcutil.AddressTaproot)
×
2181
        if isTaprootChangeAddr {
×
2182
                changeAddrInfo, err := w.cfg.Wallet.AddressInfo(changeAddr)
×
UNCOV
2183
                if err != nil {
×
UNCOV
2184
                        return 0, fmt.Errorf("could not get address info: %w",
×
UNCOV
2185
                                err)
×
UNCOV
2186
                }
×
2187

2188
                deriv, trDeriv, _, err := btcwallet.Bip32DerivationFromAddress(
×
2189
                        changeAddrInfo,
×
2190
                )
×
2191
                if err != nil {
×
2192
                        return 0, fmt.Errorf("could not get derivation info: "+
×
2193
                                "%w", err)
×
2194
                }
×
2195

UNCOV
2196
                pOut.TaprootInternalKey = trDeriv.XOnlyPubKey
×
2197
                pOut.Bip32Derivation = []*psbt.Bip32Derivation{deriv}
×
2198
                pOut.TaprootBip32Derivation = []*psbt.TaprootBip32Derivation{
×
2199
                        trDeriv,
×
2200
                }
×
2201
        }
2202

2203
        newChangeIndex := int32(len(packet.Outputs))
×
UNCOV
2204
        packet.UnsignedTx.TxOut = append(
×
2205
                packet.UnsignedTx.TxOut, &wire.TxOut{
×
2206
                        Value:    changeAmount,
×
2207
                        PkScript: changeScript,
×
2208
                },
×
2209
        )
×
UNCOV
2210
        packet.Outputs = append(packet.Outputs, pOut)
×
UNCOV
2211

×
2212
        return newChangeIndex, nil
×
2213
}
2214

2215
// marshallLeases converts the lock leases to the RPC format.
2216
func marshallLeases(locks []*base.ListLeasedOutputResult) []*UtxoLease {
3✔
2217
        rpcLocks := make([]*UtxoLease, len(locks))
3✔
2218
        for idx, lock := range locks {
6✔
2219
                lock := lock
3✔
2220

3✔
2221
                rpcLocks[idx] = &UtxoLease{
3✔
2222
                        Id:         lock.LockID[:],
3✔
2223
                        Outpoint:   lnrpc.MarshalOutPoint(&lock.Outpoint),
3✔
2224
                        Expiration: uint64(lock.Expiration.Unix()),
3✔
2225
                        PkScript:   lock.PkScript,
3✔
2226
                        Value:      uint64(lock.Value),
3✔
2227
                }
3✔
2228
        }
3✔
2229

2230
        return rpcLocks
3✔
2231
}
2232

2233
// keyScopeFromChangeAddressType maps a ChangeAddressType from protobuf to a
2234
// KeyScope. If the type is ChangeAddressType_CHANGE_ADDRESS_TYPE_UNSPECIFIED,
2235
// it returns nil.
2236
func keyScopeFromChangeAddressType(
2237
        changeAddressType ChangeAddressType) *waddrmgr.KeyScope {
3✔
2238

3✔
2239
        switch changeAddressType {
3✔
2240
        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
3✔
2241
                return &waddrmgr.KeyScopeBIP0086
3✔
2242

2243
        default:
3✔
2244
                return nil
3✔
2245
        }
2246
}
2247

2248
// addrTypeFromChangeAddressType maps a chanfunding.ChangeAddressType to the
2249
// lnwallet.AddressType.
2250
func addrTypeFromChangeAddressType(
UNCOV
2251
        changeAddressType chanfunding.ChangeAddressType) lnwallet.AddressType {
×
UNCOV
2252

×
UNCOV
2253
        switch changeAddressType {
×
UNCOV
2254
        case chanfunding.P2TRChangeAddress:
×
UNCOV
2255
                return lnwallet.TaprootPubkey
×
2256

UNCOV
2257
        default:
×
UNCOV
2258
                return lnwallet.WitnessPubKey
×
2259
        }
2260
}
2261

2262
// SignPsbt expects a partial transaction with all inputs and outputs fully
2263
// declared and tries to sign all unsigned inputs that have all required fields
2264
// (UTXO information, BIP32 derivation information, witness or sig scripts)
2265
// set.
2266
// If no error is returned, the PSBT is ready to be given to the next signer or
2267
// to be finalized if lnd was the last signer.
2268
//
2269
// NOTE: This RPC only signs inputs (and only those it can sign), it does not
2270
// perform any other tasks (such as coin selection, UTXO locking or
2271
// input/output/fee value validation, PSBT finalization). Any input that is
2272
// incomplete will be skipped.
2273
func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) (
2274
        *SignPsbtResponse, error) {
3✔
2275

3✔
2276
        packet, err := psbt.NewFromRawBytes(
3✔
2277
                bytes.NewReader(req.FundedPsbt), false,
3✔
2278
        )
3✔
2279
        if err != nil {
3✔
UNCOV
2280
                log.Debugf("Error parsing PSBT: %v, raw input: %x", err,
×
UNCOV
2281
                        req.FundedPsbt)
×
UNCOV
2282
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
UNCOV
2283
        }
×
2284

2285
        // Before we attempt to sign the packet, ensure that every input either
2286
        // has a witness UTXO, or a non witness UTXO.
2287
        for idx := range packet.UnsignedTx.TxIn {
6✔
2288
                in := packet.Inputs[idx]
3✔
2289

3✔
2290
                // Doesn't have either a witness or non witness UTXO so we need
3✔
2291
                // to exit here as otherwise signing will fail.
3✔
2292
                if in.WitnessUtxo == nil && in.NonWitnessUtxo == nil {
6✔
2293
                        return nil, fmt.Errorf("input (index=%v) doesn't "+
3✔
2294
                                "specify any UTXO info", idx)
3✔
2295
                }
3✔
2296
        }
2297

2298
        // Let the wallet do the heavy lifting. This will sign all inputs that
2299
        // we have the UTXO for. If some inputs can't be signed and don't have
2300
        // witness data attached, they will just be skipped.
2301
        signedInputs, err := w.cfg.Wallet.SignPsbt(packet)
3✔
2302
        if err != nil {
3✔
UNCOV
2303
                return nil, fmt.Errorf("error signing PSBT: %w", err)
×
UNCOV
2304
        }
×
2305

2306
        // Serialize the signed PSBT in both the packet and wire format.
2307
        var signedPsbtBytes bytes.Buffer
3✔
2308
        err = packet.Serialize(&signedPsbtBytes)
3✔
2309
        if err != nil {
3✔
UNCOV
2310
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
UNCOV
2311
        }
×
2312

2313
        return &SignPsbtResponse{
3✔
2314
                SignedPsbt:   signedPsbtBytes.Bytes(),
3✔
2315
                SignedInputs: signedInputs,
3✔
2316
        }, nil
3✔
2317
}
2318

2319
// FinalizePsbt expects a partial transaction with all inputs and outputs fully
2320
// declared and tries to sign all inputs that belong to the wallet. Lnd must be
2321
// the last signer of the transaction. That means, if there are any unsigned
2322
// non-witness inputs or inputs without UTXO information attached or inputs
2323
// without witness data that do not belong to lnd's wallet, this method will
2324
// fail. If no error is returned, the PSBT is ready to be extracted and the
2325
// final TX within to be broadcast.
2326
//
2327
// NOTE: This method does NOT publish the transaction once finalized. It is the
2328
// caller's responsibility to either publish the transaction on success or
2329
// unlock/release any locked UTXOs in case of an error in this method.
2330
func (w *WalletKit) FinalizePsbt(_ context.Context,
2331
        req *FinalizePsbtRequest) (*FinalizePsbtResponse, error) {
3✔
2332

3✔
2333
        // We'll assume the PSBT was funded by the default account unless
3✔
2334
        // otherwise specified.
3✔
2335
        account := lnwallet.DefaultAccountName
3✔
2336
        if req.Account != "" {
3✔
UNCOV
2337
                account = req.Account
×
UNCOV
2338
        }
×
2339

2340
        // Parse the funded PSBT.
2341
        packet, err := psbt.NewFromRawBytes(
3✔
2342
                bytes.NewReader(req.FundedPsbt), false,
3✔
2343
        )
3✔
2344
        if err != nil {
3✔
UNCOV
2345
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
2346
        }
×
2347

2348
        // The only check done at this level is to validate that the PSBT is
2349
        // not complete. The wallet performs all other checks.
2350
        if packet.IsComplete() {
3✔
UNCOV
2351
                return nil, fmt.Errorf("PSBT is already fully signed")
×
UNCOV
2352
        }
×
2353

2354
        // Let the wallet do the heavy lifting. This will sign all inputs that
2355
        // we have the UTXO for. If some inputs can't be signed and don't have
2356
        // witness data attached, this will fail.
2357
        err = w.cfg.Wallet.FinalizePsbt(packet, account)
3✔
2358
        if err != nil {
3✔
UNCOV
2359
                return nil, fmt.Errorf("error finalizing PSBT: %w", err)
×
2360
        }
×
2361

2362
        var (
3✔
2363
                finalPsbtBytes bytes.Buffer
3✔
2364
                finalTxBytes   bytes.Buffer
3✔
2365
        )
3✔
2366

3✔
2367
        // Serialize the finalized PSBT in both the packet and wire format.
3✔
2368
        err = packet.Serialize(&finalPsbtBytes)
3✔
2369
        if err != nil {
3✔
UNCOV
2370
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
UNCOV
2371
        }
×
2372
        finalTx, err := psbt.Extract(packet)
3✔
2373
        if err != nil {
3✔
UNCOV
2374
                return nil, fmt.Errorf("unable to extract final TX: %w", err)
×
UNCOV
2375
        }
×
2376
        err = finalTx.Serialize(&finalTxBytes)
3✔
2377
        if err != nil {
3✔
UNCOV
2378
                return nil, fmt.Errorf("error serializing final TX: %w", err)
×
2379
        }
×
2380

2381
        return &FinalizePsbtResponse{
3✔
2382
                SignedPsbt: finalPsbtBytes.Bytes(),
3✔
2383
                RawFinalTx: finalTxBytes.Bytes(),
3✔
2384
        }, nil
3✔
2385
}
2386

2387
// marshalWalletAccount converts the properties of an account into its RPC
2388
// representation.
2389
func marshalWalletAccount(internalScope waddrmgr.KeyScope,
2390
        account *waddrmgr.AccountProperties) (*Account, error) {
3✔
2391

3✔
2392
        var addrType AddressType
3✔
2393
        switch account.KeyScope {
3✔
2394
        case waddrmgr.KeyScopeBIP0049Plus:
3✔
2395
                // No address schema present represents the traditional BIP-0049
3✔
2396
                // address derivation scheme.
3✔
2397
                if account.AddrSchema == nil {
6✔
2398
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
3✔
2399
                        break
3✔
2400
                }
2401

2402
                switch *account.AddrSchema {
3✔
2403
                case waddrmgr.KeyScopeBIP0049AddrSchema:
3✔
2404
                        addrType = AddressType_NESTED_WITNESS_PUBKEY_HASH
3✔
2405

2406
                case waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0049Plus]:
3✔
2407
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
3✔
2408

UNCOV
2409
                default:
×
UNCOV
2410
                        return nil, fmt.Errorf("unsupported address schema %v",
×
UNCOV
2411
                                *account.AddrSchema)
×
2412
                }
2413

2414
        case waddrmgr.KeyScopeBIP0084:
3✔
2415
                addrType = AddressType_WITNESS_PUBKEY_HASH
3✔
2416

2417
        case waddrmgr.KeyScopeBIP0086:
3✔
2418
                addrType = AddressType_TAPROOT_PUBKEY
3✔
2419

2420
        case internalScope:
3✔
2421
                addrType = AddressType_WITNESS_PUBKEY_HASH
3✔
2422

UNCOV
2423
        default:
×
UNCOV
2424
                return nil, fmt.Errorf("account %v has unsupported "+
×
UNCOV
2425
                        "key scope %v", account.AccountName, account.KeyScope)
×
2426
        }
2427

2428
        rpcAccount := &Account{
3✔
2429
                Name:             account.AccountName,
3✔
2430
                AddressType:      addrType,
3✔
2431
                ExternalKeyCount: account.ExternalKeyCount,
3✔
2432
                InternalKeyCount: account.InternalKeyCount,
3✔
2433
                WatchOnly:        account.IsWatchOnly,
3✔
2434
        }
3✔
2435

3✔
2436
        // The remaining fields can only be done on accounts other than the
3✔
2437
        // default imported one existing within each key scope.
3✔
2438
        if account.AccountName != waddrmgr.ImportedAddrAccountName {
6✔
2439
                nonHardenedIndex := account.AccountPubKey.ChildIndex() -
3✔
2440
                        hdkeychain.HardenedKeyStart
3✔
2441
                rpcAccount.ExtendedPublicKey = account.AccountPubKey.String()
3✔
2442
                if account.MasterKeyFingerprint != 0 {
3✔
UNCOV
2443
                        var mkfp [4]byte
×
UNCOV
2444
                        binary.BigEndian.PutUint32(
×
UNCOV
2445
                                mkfp[:], account.MasterKeyFingerprint,
×
UNCOV
2446
                        )
×
UNCOV
2447
                        rpcAccount.MasterKeyFingerprint = mkfp[:]
×
UNCOV
2448
                }
×
2449
                rpcAccount.DerivationPath = fmt.Sprintf("%v/%v'",
3✔
2450
                        account.KeyScope, nonHardenedIndex)
3✔
2451
        }
2452

2453
        return rpcAccount, nil
3✔
2454
}
2455

2456
// marshalWalletAddressList converts the list of address into its RPC
2457
// representation.
2458
func marshalWalletAddressList(w *WalletKit, account *waddrmgr.AccountProperties,
2459
        addressList []lnwallet.AddressProperty) (*AccountWithAddresses, error) {
3✔
2460

3✔
2461
        // Get the RPC representation of account.
3✔
2462
        rpcAccount, err := marshalWalletAccount(
3✔
2463
                w.internalScope(), account,
3✔
2464
        )
3✔
2465
        if err != nil {
3✔
UNCOV
2466
                return nil, err
×
UNCOV
2467
        }
×
2468

2469
        addresses := make([]*AddressProperty, len(addressList))
3✔
2470
        for idx, addr := range addressList {
6✔
2471
                var pubKeyBytes []byte
3✔
2472
                if addr.PublicKey != nil {
6✔
2473
                        pubKeyBytes = addr.PublicKey.SerializeCompressed()
3✔
2474
                }
3✔
2475
                addresses[idx] = &AddressProperty{
3✔
2476
                        Address:        addr.Address,
3✔
2477
                        IsInternal:     addr.Internal,
3✔
2478
                        Balance:        int64(addr.Balance),
3✔
2479
                        DerivationPath: addr.DerivationPath,
3✔
2480
                        PublicKey:      pubKeyBytes,
3✔
2481
                }
3✔
2482
        }
2483

2484
        rpcAddressList := &AccountWithAddresses{
3✔
2485
                Name:           rpcAccount.Name,
3✔
2486
                AddressType:    rpcAccount.AddressType,
3✔
2487
                DerivationPath: rpcAccount.DerivationPath,
3✔
2488
                Addresses:      addresses,
3✔
2489
        }
3✔
2490

3✔
2491
        return rpcAddressList, nil
3✔
2492
}
2493

2494
// ListAccounts retrieves all accounts belonging to the wallet by default. A
2495
// name and key scope filter can be provided to filter through all of the wallet
2496
// accounts and return only those matching.
2497
func (w *WalletKit) ListAccounts(ctx context.Context,
2498
        req *ListAccountsRequest) (*ListAccountsResponse, error) {
3✔
2499

3✔
2500
        // Map the supported address types into their corresponding key scope.
3✔
2501
        var keyScopeFilter *waddrmgr.KeyScope
3✔
2502
        switch req.AddressType {
3✔
2503
        case AddressType_UNKNOWN:
3✔
2504
                break
3✔
2505

2506
        case AddressType_WITNESS_PUBKEY_HASH:
3✔
2507
                keyScope := waddrmgr.KeyScopeBIP0084
3✔
2508
                keyScopeFilter = &keyScope
3✔
2509

2510
        case AddressType_NESTED_WITNESS_PUBKEY_HASH,
2511
                AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
3✔
2512

3✔
2513
                keyScope := waddrmgr.KeyScopeBIP0049Plus
3✔
2514
                keyScopeFilter = &keyScope
3✔
2515

2516
        case AddressType_TAPROOT_PUBKEY:
3✔
2517
                keyScope := waddrmgr.KeyScopeBIP0086
3✔
2518
                keyScopeFilter = &keyScope
3✔
2519

UNCOV
2520
        default:
×
UNCOV
2521
                return nil, fmt.Errorf("unhandled address type %v",
×
UNCOV
2522
                        req.AddressType)
×
2523
        }
2524

2525
        accounts, err := w.cfg.Wallet.ListAccounts(req.Name, keyScopeFilter)
3✔
2526
        if err != nil {
3✔
UNCOV
2527
                return nil, err
×
UNCOV
2528
        }
×
2529

2530
        rpcAccounts := make([]*Account, 0, len(accounts))
3✔
2531
        for _, account := range accounts {
6✔
2532
                // Don't include the default imported accounts created by the
3✔
2533
                // wallet in the response if they don't have any keys imported.
3✔
2534
                if account.AccountName == waddrmgr.ImportedAddrAccountName &&
3✔
2535
                        account.ImportedKeyCount == 0 {
6✔
2536

3✔
2537
                        continue
3✔
2538
                }
2539

2540
                rpcAccount, err := marshalWalletAccount(
3✔
2541
                        w.internalScope(), account,
3✔
2542
                )
3✔
2543
                if err != nil {
3✔
UNCOV
2544
                        return nil, err
×
UNCOV
2545
                }
×
2546
                rpcAccounts = append(rpcAccounts, rpcAccount)
3✔
2547
        }
2548

2549
        return &ListAccountsResponse{Accounts: rpcAccounts}, nil
3✔
2550
}
2551

2552
// RequiredReserve returns the minimum amount of satoshis that should be
2553
// kept in the wallet in order to fee bump anchor channels if necessary.
2554
// The value scales with the number of public anchor channels but is
2555
// capped at a maximum.
2556
func (w *WalletKit) RequiredReserve(ctx context.Context,
2557
        req *RequiredReserveRequest) (*RequiredReserveResponse, error) {
3✔
2558

3✔
2559
        numAnchorChans, err := w.cfg.CurrentNumAnchorChans()
3✔
2560
        if err != nil {
3✔
UNCOV
2561
                return nil, err
×
UNCOV
2562
        }
×
2563

2564
        additionalChans := req.AdditionalPublicChannels
3✔
2565
        totalChans := uint32(numAnchorChans) + additionalChans
3✔
2566
        reserved := w.cfg.Wallet.RequiredReserve(totalChans)
3✔
2567

3✔
2568
        return &RequiredReserveResponse{
3✔
2569
                RequiredReserve: int64(reserved),
3✔
2570
        }, nil
3✔
2571
}
2572

2573
// ListAddresses retrieves all the addresses along with their balance. An
2574
// account name filter can be provided to filter through all of the
2575
// wallet accounts and return the addresses of only those matching.
2576
func (w *WalletKit) ListAddresses(ctx context.Context,
2577
        req *ListAddressesRequest) (*ListAddressesResponse, error) {
3✔
2578

3✔
2579
        addressLists, err := w.cfg.Wallet.ListAddresses(
3✔
2580
                req.AccountName,
3✔
2581
                req.ShowCustomAccounts,
3✔
2582
        )
3✔
2583
        if err != nil {
3✔
UNCOV
2584
                return nil, err
×
UNCOV
2585
        }
×
2586

2587
        // Create a slice of accounts from addressLists map.
2588
        accounts := make([]*waddrmgr.AccountProperties, 0, len(addressLists))
3✔
2589
        for account := range addressLists {
6✔
2590
                accounts = append(accounts, account)
3✔
2591
        }
3✔
2592

2593
        // Sort the accounts by derivation path.
2594
        sort.Slice(accounts, func(i, j int) bool {
6✔
2595
                scopeI := accounts[i].KeyScope
3✔
2596
                scopeJ := accounts[j].KeyScope
3✔
2597
                if scopeI.Purpose == scopeJ.Purpose {
3✔
UNCOV
2598
                        if scopeI.Coin == scopeJ.Coin {
×
UNCOV
2599
                                acntNumI := accounts[i].AccountNumber
×
UNCOV
2600
                                acntNumJ := accounts[j].AccountNumber
×
UNCOV
2601
                                return acntNumI < acntNumJ
×
UNCOV
2602
                        }
×
2603

UNCOV
2604
                        return scopeI.Coin < scopeJ.Coin
×
2605
                }
2606

2607
                return scopeI.Purpose < scopeJ.Purpose
3✔
2608
        })
2609

2610
        rpcAddressLists := make([]*AccountWithAddresses, 0, len(addressLists))
3✔
2611
        for _, account := range accounts {
6✔
2612
                addressList := addressLists[account]
3✔
2613
                rpcAddressList, err := marshalWalletAddressList(
3✔
2614
                        w, account, addressList,
3✔
2615
                )
3✔
2616
                if err != nil {
3✔
UNCOV
2617
                        return nil, err
×
UNCOV
2618
                }
×
2619

2620
                rpcAddressLists = append(rpcAddressLists, rpcAddressList)
3✔
2621
        }
2622

2623
        return &ListAddressesResponse{
3✔
2624
                AccountWithAddresses: rpcAddressLists,
3✔
2625
        }, nil
3✔
2626
}
2627

2628
// parseAddrType parses an address type from its RPC representation to a
2629
// *waddrmgr.AddressType.
2630
func parseAddrType(addrType AddressType,
2631
        required bool) (*waddrmgr.AddressType, error) {
3✔
2632

3✔
2633
        switch addrType {
3✔
UNCOV
2634
        case AddressType_UNKNOWN:
×
UNCOV
2635
                if required {
×
UNCOV
2636
                        return nil, fmt.Errorf("an address type must be " +
×
UNCOV
2637
                                "specified")
×
UNCOV
2638
                }
×
UNCOV
2639
                return nil, nil
×
2640

2641
        case AddressType_WITNESS_PUBKEY_HASH:
3✔
2642
                addrTyp := waddrmgr.WitnessPubKey
3✔
2643
                return &addrTyp, nil
3✔
2644

2645
        case AddressType_NESTED_WITNESS_PUBKEY_HASH:
3✔
2646
                addrTyp := waddrmgr.NestedWitnessPubKey
3✔
2647
                return &addrTyp, nil
3✔
2648

2649
        case AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
3✔
2650
                addrTyp := waddrmgr.WitnessPubKey
3✔
2651
                return &addrTyp, nil
3✔
2652

2653
        case AddressType_TAPROOT_PUBKEY:
3✔
2654
                addrTyp := waddrmgr.TaprootPubKey
3✔
2655
                return &addrTyp, nil
3✔
2656

UNCOV
2657
        default:
×
UNCOV
2658
                return nil, fmt.Errorf("unhandled address type %v", addrType)
×
2659
        }
2660
}
2661

2662
// msgSignaturePrefix is a prefix used to prevent inadvertently signing a
2663
// transaction or a signature. It is prepended in front of the message and
2664
// follows the same standard as bitcoin core and btcd.
2665
const msgSignaturePrefix = "Bitcoin Signed Message:\n"
2666

2667
// SignMessageWithAddr signs a message with the private key of the provided
2668
// address. The address needs to belong to the lnd wallet.
2669
func (w *WalletKit) SignMessageWithAddr(_ context.Context,
2670
        req *SignMessageWithAddrRequest) (*SignMessageWithAddrResponse, error) {
3✔
2671

3✔
2672
        addr, err := btcutil.DecodeAddress(req.Addr, w.cfg.ChainParams)
3✔
2673
        if err != nil {
3✔
UNCOV
2674
                return nil, fmt.Errorf("unable to decode address: %w", err)
×
UNCOV
2675
        }
×
2676

2677
        if !addr.IsForNet(w.cfg.ChainParams) {
3✔
UNCOV
2678
                return nil, fmt.Errorf("encoded address is for "+
×
UNCOV
2679
                        "the wrong network %s", req.Addr)
×
UNCOV
2680
        }
×
2681

2682
        // Fetch address infos from own wallet and check whether it belongs
2683
        // to the lnd wallet.
2684
        managedAddr, err := w.cfg.Wallet.AddressInfo(addr)
3✔
2685
        if err != nil {
3✔
UNCOV
2686
                return nil, fmt.Errorf("address could not be found in the "+
×
2687
                        "wallet database: %w", err)
×
2688
        }
×
2689

2690
        // Verifying by checking the interface type that the wallet knows about
2691
        // the public and private keys so it can sign the message with the
2692
        // private key of this address.
2693
        pubKey, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
3✔
2694
        if !ok {
3✔
2695
                return nil, fmt.Errorf("private key to address is unknown")
×
2696
        }
×
2697

2698
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
3✔
2699
        if err != nil {
3✔
UNCOV
2700
                return nil, err
×
UNCOV
2701
        }
×
2702

2703
        // For all address types (P2WKH, NP2WKH,P2TR) the ECDSA compact signing
2704
        // algorithm is used. For P2TR addresses this represents a special case.
2705
        // ECDSA is used to create a compact signature which makes the public
2706
        // key of the signature recoverable. For Schnorr no known compact
2707
        // signing algorithm exists yet.
2708
        privKey, err := pubKey.PrivKey()
3✔
2709
        if err != nil {
3✔
2710
                return nil, fmt.Errorf("no private key could be "+
×
UNCOV
2711
                        "fetched from wallet database: %w", err)
×
UNCOV
2712
        }
×
2713

2714
        sigBytes := ecdsa.SignCompact(privKey, digest, pubKey.Compressed())
3✔
2715

3✔
2716
        // Bitcoin signatures are base64 encoded (being compatible with
3✔
2717
        // bitcoin-core and btcd).
3✔
2718
        sig := base64.StdEncoding.EncodeToString(sigBytes)
3✔
2719

3✔
2720
        return &SignMessageWithAddrResponse{
3✔
2721
                Signature: sig,
3✔
2722
        }, nil
3✔
2723
}
2724

2725
// VerifyMessageWithAddr verifies a signature on a message with a provided
2726
// address, it checks both the validity of the signature itself and then
2727
// verifies whether the signature corresponds to the public key of the
2728
// provided address. There is no dependence on the private key of the address
2729
// therefore also external addresses are allowed to verify signatures.
2730
// Supported address types are P2PKH, P2WKH, NP2WKH, P2TR.
2731
func (w *WalletKit) VerifyMessageWithAddr(_ context.Context,
2732
        req *VerifyMessageWithAddrRequest) (*VerifyMessageWithAddrResponse,
2733
        error) {
3✔
2734

3✔
2735
        sig, err := base64.StdEncoding.DecodeString(req.Signature)
3✔
2736
        if err != nil {
3✔
UNCOV
2737
                return nil, fmt.Errorf("malformed base64 encoding of "+
×
UNCOV
2738
                        "the signature: %w", err)
×
UNCOV
2739
        }
×
2740

2741
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
3✔
2742
        if err != nil {
3✔
UNCOV
2743
                return nil, err
×
UNCOV
2744
        }
×
2745

2746
        pk, wasCompressed, err := ecdsa.RecoverCompact(sig, digest)
3✔
2747
        if err != nil {
3✔
2748
                return nil, fmt.Errorf("unable to recover public key "+
×
UNCOV
2749
                        "from compact signature: %w", err)
×
UNCOV
2750
        }
×
2751

2752
        var serializedPubkey []byte
3✔
2753
        if wasCompressed {
6✔
2754
                serializedPubkey = pk.SerializeCompressed()
3✔
2755
        } else {
3✔
UNCOV
2756
                serializedPubkey = pk.SerializeUncompressed()
×
2757
        }
×
2758

2759
        addr, err := btcutil.DecodeAddress(req.Addr, w.cfg.ChainParams)
3✔
2760
        if err != nil {
3✔
UNCOV
2761
                return nil, fmt.Errorf("unable to decode address: %w", err)
×
UNCOV
2762
        }
×
2763

2764
        if !addr.IsForNet(w.cfg.ChainParams) {
3✔
2765
                return nil, fmt.Errorf("encoded address is for"+
×
2766
                        "the wrong network %s", req.Addr)
×
UNCOV
2767
        }
×
2768

2769
        var (
3✔
2770
                address    btcutil.Address
3✔
2771
                pubKeyHash = btcutil.Hash160(serializedPubkey)
3✔
2772
        )
3✔
2773

3✔
2774
        // Ensure the address is one of the supported types.
3✔
2775
        switch addr.(type) {
3✔
2776
        case *btcutil.AddressPubKeyHash:
3✔
2777
                address, err = btcutil.NewAddressPubKeyHash(
3✔
2778
                        pubKeyHash, w.cfg.ChainParams,
3✔
2779
                )
3✔
2780
                if err != nil {
3✔
UNCOV
2781
                        return nil, err
×
UNCOV
2782
                }
×
2783

2784
        case *btcutil.AddressWitnessPubKeyHash:
3✔
2785
                address, err = btcutil.NewAddressWitnessPubKeyHash(
3✔
2786
                        pubKeyHash, w.cfg.ChainParams,
3✔
2787
                )
3✔
2788
                if err != nil {
3✔
UNCOV
2789
                        return nil, err
×
2790
                }
×
2791

2792
        case *btcutil.AddressScriptHash:
3✔
2793
                // Check if address is a Nested P2WKH (NP2WKH).
3✔
2794
                address, err = btcutil.NewAddressWitnessPubKeyHash(
3✔
2795
                        pubKeyHash, w.cfg.ChainParams,
3✔
2796
                )
3✔
2797
                if err != nil {
3✔
2798
                        return nil, err
×
2799
                }
×
2800

2801
                witnessScript, err := txscript.PayToAddrScript(address)
3✔
2802
                if err != nil {
3✔
UNCOV
2803
                        return nil, err
×
UNCOV
2804
                }
×
2805

2806
                address, err = btcutil.NewAddressScriptHashFromHash(
3✔
2807
                        btcutil.Hash160(witnessScript), w.cfg.ChainParams,
3✔
2808
                )
3✔
2809
                if err != nil {
3✔
UNCOV
2810
                        return nil, err
×
UNCOV
2811
                }
×
2812

2813
        case *btcutil.AddressTaproot:
3✔
2814
                // Only addresses without a tapscript are allowed because
3✔
2815
                // the verification is using the internal key.
3✔
2816
                tapKey := txscript.ComputeTaprootKeyNoScript(pk)
3✔
2817
                address, err = btcutil.NewAddressTaproot(
3✔
2818
                        schnorr.SerializePubKey(tapKey),
3✔
2819
                        w.cfg.ChainParams,
3✔
2820
                )
3✔
2821
                if err != nil {
3✔
UNCOV
2822
                        return nil, err
×
UNCOV
2823
                }
×
2824

UNCOV
2825
        default:
×
UNCOV
2826
                return nil, fmt.Errorf("unsupported address type")
×
2827
        }
2828

2829
        return &VerifyMessageWithAddrResponse{
3✔
2830
                Valid:  req.Addr == address.EncodeAddress(),
3✔
2831
                Pubkey: serializedPubkey,
3✔
2832
        }, nil
3✔
2833
}
2834

2835
// ImportAccount imports an account backed by an account extended public key.
2836
// The master key fingerprint denotes the fingerprint of the root key
2837
// corresponding to the account public key (also known as the key with
2838
// derivation path m/). This may be required by some hardware wallets for proper
2839
// identification and signing.
2840
//
2841
// The address type can usually be inferred from the key's version, but may be
2842
// required for certain keys to map them into the proper scope.
2843
//
2844
// For BIP-0044 keys, an address type must be specified as we intend to not
2845
// support importing BIP-0044 keys into the wallet using the legacy
2846
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force
2847
// the standard BIP-0049 derivation scheme, while a witness address type will
2848
// force the standard BIP-0084 derivation scheme.
2849
//
2850
// For BIP-0049 keys, an address type must also be specified to make a
2851
// distinction between the standard BIP-0049 address schema (nested witness
2852
// pubkeys everywhere) and our own BIP-0049Plus address schema (nested pubkeys
2853
// externally, witness pubkeys internally).
2854
func (w *WalletKit) ImportAccount(_ context.Context,
2855
        req *ImportAccountRequest) (*ImportAccountResponse, error) {
3✔
2856

3✔
2857
        accountPubKey, err := hdkeychain.NewKeyFromString(req.ExtendedPublicKey)
3✔
2858
        if err != nil {
3✔
UNCOV
2859
                return nil, err
×
UNCOV
2860
        }
×
2861

2862
        var mkfp uint32
3✔
2863
        switch len(req.MasterKeyFingerprint) {
3✔
2864
        // No master key fingerprint provided, which is fine as it's not
2865
        // required.
2866
        case 0:
3✔
2867
        // Expected length.
2868
        case 4:
×
2869
                mkfp = binary.BigEndian.Uint32(req.MasterKeyFingerprint)
×
UNCOV
2870
        default:
×
UNCOV
2871
                return nil, errors.New("invalid length for master key " +
×
UNCOV
2872
                        "fingerprint, expected 4 bytes in big-endian")
×
2873
        }
2874

2875
        addrType, err := parseAddrType(req.AddressType, false)
3✔
2876
        if err != nil {
3✔
2877
                return nil, err
×
2878
        }
×
2879

2880
        accountProps, extAddrs, intAddrs, err := w.cfg.Wallet.ImportAccount(
3✔
2881
                req.Name, accountPubKey, mkfp, addrType, req.DryRun,
3✔
2882
        )
3✔
2883
        if err != nil {
6✔
2884
                return nil, err
3✔
2885
        }
3✔
2886

2887
        rpcAccount, err := marshalWalletAccount(w.internalScope(), accountProps)
3✔
2888
        if err != nil {
3✔
UNCOV
2889
                return nil, err
×
UNCOV
2890
        }
×
2891

2892
        resp := &ImportAccountResponse{Account: rpcAccount}
3✔
2893
        if !req.DryRun {
6✔
2894
                return resp, nil
3✔
2895
        }
3✔
2896

UNCOV
2897
        resp.DryRunExternalAddrs = make([]string, len(extAddrs))
×
2898
        for i := 0; i < len(extAddrs); i++ {
×
2899
                resp.DryRunExternalAddrs[i] = extAddrs[i].String()
×
UNCOV
2900
        }
×
UNCOV
2901
        resp.DryRunInternalAddrs = make([]string, len(intAddrs))
×
UNCOV
2902
        for i := 0; i < len(intAddrs); i++ {
×
UNCOV
2903
                resp.DryRunInternalAddrs[i] = intAddrs[i].String()
×
UNCOV
2904
        }
×
2905

2906
        return resp, nil
×
2907
}
2908

2909
// ImportPublicKey imports a single derived public key into the wallet. The
2910
// address type can usually be inferred from the key's version, but in the case
2911
// of legacy versions (xpub, tpub), an address type must be specified as we
2912
// intend to not support importing BIP-44 keys into the wallet using the legacy
2913
// pay-to-pubkey-hash (P2PKH) scheme. For Taproot keys, this will only watch
2914
// the BIP-0086 style output script. Use ImportTapscript for more advanced key
2915
// spend or script spend outputs.
2916
func (w *WalletKit) ImportPublicKey(_ context.Context,
2917
        req *ImportPublicKeyRequest) (*ImportPublicKeyResponse, error) {
3✔
2918

3✔
2919
        var (
3✔
2920
                pubKey *btcec.PublicKey
3✔
2921
                err    error
3✔
2922
        )
3✔
2923
        switch req.AddressType {
3✔
2924
        case AddressType_TAPROOT_PUBKEY:
3✔
2925
                pubKey, err = schnorr.ParsePubKey(req.PublicKey)
3✔
2926

2927
        default:
3✔
2928
                pubKey, err = btcec.ParsePubKey(req.PublicKey)
3✔
2929
        }
2930
        if err != nil {
3✔
UNCOV
2931
                return nil, err
×
UNCOV
2932
        }
×
2933

2934
        addrType, err := parseAddrType(req.AddressType, true)
3✔
2935
        if err != nil {
3✔
UNCOV
2936
                return nil, err
×
UNCOV
2937
        }
×
2938

2939
        if err := w.cfg.Wallet.ImportPublicKey(pubKey, *addrType); err != nil {
3✔
2940
                return nil, err
×
2941
        }
×
2942

2943
        return &ImportPublicKeyResponse{
3✔
2944
                Status: fmt.Sprintf("public key %x imported",
3✔
2945
                        pubKey.SerializeCompressed()),
3✔
2946
        }, nil
3✔
2947
}
2948

2949
// ImportTapscript imports a Taproot script and internal key and adds the
2950
// resulting Taproot output key as a watch-only output script into the wallet.
2951
// For BIP-0086 style Taproot keys (no root hash commitment and no script spend
2952
// path) use ImportPublicKey.
2953
//
2954
// NOTE: Taproot keys imported through this RPC currently _cannot_ be used for
2955
// funding PSBTs. Only tracking the balance and UTXOs is currently supported.
2956
func (w *WalletKit) ImportTapscript(_ context.Context,
2957
        req *ImportTapscriptRequest) (*ImportTapscriptResponse, error) {
3✔
2958

3✔
2959
        internalKey, err := schnorr.ParsePubKey(req.InternalPublicKey)
3✔
2960
        if err != nil {
3✔
UNCOV
2961
                return nil, fmt.Errorf("error parsing internal key: %w", err)
×
UNCOV
2962
        }
×
2963

2964
        var tapscript *waddrmgr.Tapscript
3✔
2965
        switch {
3✔
2966
        case req.GetFullTree() != nil:
3✔
2967
                tree := req.GetFullTree()
3✔
2968
                leaves := make([]txscript.TapLeaf, len(tree.AllLeaves))
3✔
2969
                for idx, leaf := range tree.AllLeaves {
6✔
2970
                        leaves[idx] = txscript.TapLeaf{
3✔
2971
                                LeafVersion: txscript.TapscriptLeafVersion(
3✔
2972
                                        leaf.LeafVersion,
3✔
2973
                                ),
3✔
2974
                                Script: leaf.Script,
3✔
2975
                        }
3✔
2976
                }
3✔
2977

2978
                tapscript = input.TapscriptFullTree(internalKey, leaves...)
3✔
2979

2980
        case req.GetPartialReveal() != nil:
3✔
2981
                partialReveal := req.GetPartialReveal()
3✔
2982
                if partialReveal.RevealedLeaf == nil {
3✔
UNCOV
2983
                        return nil, fmt.Errorf("missing revealed leaf")
×
UNCOV
2984
                }
×
2985

2986
                revealedLeaf := txscript.TapLeaf{
3✔
2987
                        LeafVersion: txscript.TapscriptLeafVersion(
3✔
2988
                                partialReveal.RevealedLeaf.LeafVersion,
3✔
2989
                        ),
3✔
2990
                        Script: partialReveal.RevealedLeaf.Script,
3✔
2991
                }
3✔
2992
                if len(partialReveal.FullInclusionProof)%32 != 0 {
3✔
2993
                        return nil, fmt.Errorf("invalid inclusion proof "+
×
UNCOV
2994
                                "length, expected multiple of 32, got %d",
×
UNCOV
2995
                                len(partialReveal.FullInclusionProof)%32)
×
UNCOV
2996
                }
×
2997

2998
                tapscript = input.TapscriptPartialReveal(
3✔
2999
                        internalKey, revealedLeaf,
3✔
3000
                        partialReveal.FullInclusionProof,
3✔
3001
                )
3✔
3002

3003
        case req.GetRootHashOnly() != nil:
3✔
3004
                rootHash := req.GetRootHashOnly()
3✔
3005
                if len(rootHash) == 0 {
3✔
UNCOV
3006
                        return nil, fmt.Errorf("missing root hash")
×
UNCOV
3007
                }
×
3008

3009
                tapscript = input.TapscriptRootHashOnly(internalKey, rootHash)
3✔
3010

3011
        case req.GetFullKeyOnly():
3✔
3012
                tapscript = input.TapscriptFullKeyOnly(internalKey)
3✔
3013

UNCOV
3014
        default:
×
3015
                return nil, fmt.Errorf("invalid script")
×
3016
        }
3017

3018
        taprootScope := waddrmgr.KeyScopeBIP0086
3✔
3019
        addr, err := w.cfg.Wallet.ImportTaprootScript(taprootScope, tapscript)
3✔
3020
        if err != nil {
3✔
UNCOV
3021
                return nil, fmt.Errorf("error importing script into wallet: %w",
×
UNCOV
3022
                        err)
×
3023
        }
×
3024

3025
        return &ImportTapscriptResponse{
3✔
3026
                P2TrAddress: addr.Address().String(),
3✔
3027
        }, nil
3✔
3028
}
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