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

lightningnetwork / lnd / 16347973804

17 Jul 2025 02:31PM UTC coverage: 56.997% (-0.6%) from 57.577%
16347973804

Pull #10087

github

web-flow
Merge d1583a75d into 47e9f05dd
Pull Request #10087: walletrpc: allow conf_target=1 in EstimateFee

3 of 5 new or added lines in 1 file covered. (60.0%)

1053 existing lines in 33 files now uncovered.

97684 of 171385 relevant lines covered (57.0%)

1.2 hits per line

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

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

4
package walletrpc
5

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

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

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

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

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

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

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

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

257
        cfg *Config
258
}
259

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

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

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

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

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

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

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

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

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

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

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

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

2✔
347
        return nil
2✔
348
}
2✔
349

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
846
        // A confirmation target of zero doesn't make any sense.
2✔
847
        if req.ConfTarget == 0 {
4✔
848
                return nil, fmt.Errorf("confirmation target must be greater " +
2✔
849
                        "than 0")
2✔
850
        }
2✔
851

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

859
        relayFeePerKw := w.cfg.FeeEstimator.RelayFeePerKW()
2✔
860

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

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

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

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

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

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

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

918
        return &PendingSweepsResponse{
2✔
919
                PendingSweeps: rpcPendingSweeps,
2✔
920
        }, nil
2✔
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) {
2✔
926
        if op == nil {
2✔
927
                return nil, fmt.Errorf("empty outpoint provided")
×
928
        }
×
929

930
        var hash chainhash.Hash
2✔
931
        switch {
2✔
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:
2✔
939
                copy(hash[:], op.TxidBytes)
2✔
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{
2✔
951
                Hash:  hash,
2✔
952
                Index: op.OutputIndex,
2✔
953
        }, nil
2✔
954
}
955

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

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

2✔
964
        // We only allow using either the deprecated field or the new field.
2✔
965
        switch {
2✔
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.
985
        if in.TargetConf != 0 && !satPerKwOpt.IsNone() {
2✔
986
                return satPerKwOpt, false,
×
987
                        fmt.Errorf("either TargetConf or SatPerVbyte should " +
×
988
                                "be set, to specify the starting fee rate of " +
×
989
                                "the fee function")
×
990
        }
×
991

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

1004
                // Set the starting fee rate to the estimated fee rate.
1005
                satPerKwOpt = fn.Some(startingFeeRate)
2✔
1006
        }
1007

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

1014
        case in.Force:
×
1015
                immediate = in.Force
×
1016

1017
        case in.Immediate:
2✔
1018
                immediate = in.Immediate
2✔
1019
        }
1020

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

1026
        return satPerKwOpt, immediate, nil
2✔
1027
}
1028

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

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

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

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

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

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

1070
                return params, ok, nil
2✔
1071
        }
1072

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

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

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

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

1097
        startingFeeRate := inp.Params.StartingFeeRate
2✔
1098

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

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

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

2✔
1119
        return params, ok, nil
2✔
1120
}
1121

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

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

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

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

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

1161
                return &BumpFeeResponse{
2✔
1162
                        Status: "Successfully registered rbf-tx with sweeper",
2✔
1163
                }, nil
2✔
1164
        }
1165

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

1172
        return &BumpFeeResponse{
2✔
1173
                Status: "Successfully registered CPFP-tx with the sweeper",
2✔
1174
        }, nil
2✔
1175
}
1176

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

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

1189
        channel := fn.Find(chans, func(c *channeldb.OpenChannel) bool {
4✔
1190
                return c.FundingOutpoint == chanPoint
2✔
1191
        })
2✔
1192

1193
        return channel.UnwrapOrErr(errors.New("channel not found"))
2✔
1194
}
1195

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

2✔
1205
        if in.ChanPoint == nil {
2✔
1206
                return nil, fmt.Errorf("no chan_point provided")
×
1207
        }
×
1208

1209
        lnrpcOutpoint, err := lnrpc.GetChannelOutPoint(in.ChanPoint)
2✔
1210
        if err != nil {
2✔
1211
                return nil, err
×
1212
        }
×
1213

1214
        outPoint, err := UnmarshallOutPoint(lnrpcOutpoint)
2✔
1215
        if err != nil {
2✔
1216
                return nil, err
×
1217
        }
×
1218

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

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

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

2✔
1236
        if channel.LocalCommitment.CommitTx != nil {
4✔
1237
                localTxID := channel.LocalCommitment.CommitTx.TxHash()
2✔
1238
                commitSet.Add(localTxID)
2✔
1239
        }
2✔
1240

1241
        if channel.RemoteCommitment.CommitTx != nil {
4✔
1242
                remoteTxID := channel.RemoteCommitment.CommitTx.TxHash()
2✔
1243
                commitSet.Add(remoteTxID)
2✔
1244
        }
2✔
1245

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

1253
        if remoteCommitDiff != nil {
2✔
1254
                hash := remoteCommitDiff.Commitment.CommitTx.TxHash()
×
1255
                commitSet.Add(hash)
×
1256
        }
×
1257

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

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

1272
        pendingSweeps := slices.Collect(maps.Values(inputsMap))
2✔
1273

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

1289
                        return commitSet.Contains(sweep.OutPoint.Hash)
2✔
1290
                },
1291
        )
1292

1293
        if len(anchors) == 0 {
2✔
1294
                return nil, fmt.Errorf("unable to find pending anchor outputs")
×
1295
        }
×
1296

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

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

1328
                _, err = w.cfg.Sweeper.UpdateParams(anchor.OutPoint, params)
2✔
1329
                if err != nil {
2✔
1330
                        return nil, err
×
1331
                }
×
1332
        }
1333

1334
        return &BumpForceCloseFeeResponse{
2✔
1335
                Status: "Successfully registered anchor-cpfp transaction to" +
2✔
1336
                        "bump channel force close transaction",
2✔
1337
        }, nil
2✔
1338
}
1339

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

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

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

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

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

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

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

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

1407
        log.Infof("[BumpFee]: bumping fee for new input=%v, params=%v", op,
2✔
1408
                params)
2✔
1409

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

1415
        return nil
2✔
1416
}
1417

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

2✔
1422
        sweeps, err := w.cfg.Sweeper.ListSweeps()
2✔
1423
        if err != nil {
2✔
1424
                return nil, err
×
1425
        }
×
1426

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

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

1445
        var (
2✔
1446
                txids     []string
2✔
1447
                txDetails []*lnwallet.TransactionDetail
2✔
1448
        )
2✔
1449

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

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

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

1475
        return &ListSweepsResponse{
2✔
1476
                Sweeps: &ListSweepsResponse_TransactionIds{
2✔
1477
                        TransactionIds: &ListSweepsResponse_TransactionIDs{
2✔
1478
                                TransactionIds: txids,
2✔
1479
                        },
2✔
1480
                },
2✔
1481
        }, nil
2✔
1482
}
1483

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

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

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

1500
        hash, err := chainhash.NewHash(req.Txid)
2✔
1501
        if err != nil {
2✔
1502
                return nil, err
×
1503
        }
×
1504

1505
        err = w.cfg.Wallet.LabelTransaction(*hash, req.Label, req.Overwrite)
2✔
1506

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

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

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

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

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

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

1577
        case req.GetSatPerKw() != 0:
×
1578
                feeSatPerKW = chainfee.SatPerKWeight(req.GetSatPerKw())
×
1579

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

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

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

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

1610
                copy(lockID[:], req.CustomLockId)
2✔
1611
                customLockID = &lockID
2✔
1612
        }
1613

1614
        var customLockDuration time.Duration
2✔
1615
        if req.LockExpirationSeconds != 0 {
4✔
1616
                customLockDuration = time.Duration(req.LockExpirationSeconds) *
2✔
1617
                        time.Second
2✔
1618
        }
2✔
1619

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

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

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

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

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

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

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

1681
                        changeIndex = t.ExistingOutputIndex
2✔
1682

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

1690
                        changeType = chanfunding.ExistingChangeAddress
2✔
1691

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

1703
                        default:
×
1704
                                changeType = chanfunding.P2WKHChangeAddress
×
1705
                        }
1706

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

1711
                maxFeeRatio := chanfunding.DefaultMaxFeeRatio
2✔
1712

2✔
1713
                if req.MaxFeeRatio != 0 {
2✔
1714
                        maxFeeRatio = req.MaxFeeRatio
×
1715
                }
×
1716

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

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

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

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

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

1753
                        txOut = append(txOut, &wire.TxOut{
2✔
1754
                                Value:    int64(amt),
2✔
1755
                                PkScript: pkScript,
2✔
1756
                        })
2✔
1757
                }
1758

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

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

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

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

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

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

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

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

2✔
1831
                                        return false
2✔
1832
                                }
2✔
1833

1834
                                return true
×
1835
                        }
1836

1837
                        eligibleUtxos := fn.Filter(utxos, filterFn)
2✔
1838

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

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

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

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

1880
                        return allowed
2✔
1881
                }
1882

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

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

1908
                response, err = w.lockAndCreateFundingResponse(
2✔
1909
                        packet, outpoints, changeIndex, customLockID,
2✔
1910
                        customLockDuration,
2✔
1911
                )
2✔
1912

2✔
1913
                return err
2✔
1914
        })
1915
        if err != nil {
4✔
1916
                return nil, err
2✔
1917
        }
2✔
1918

1919
        return response, nil
2✔
1920
}
1921

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

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

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

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

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

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

2✔
1973
                estimator.AddOutput(out.PkScript)
2✔
1974
                outputSum += btcutil.Amount(out.Value)
2✔
1975
        }
2✔
1976

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

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

1988
        case chanfunding.P2WKHChangeAddress:
×
1989
                changeDustLimit = lnwallet.DustLimitForSize(input.P2WPKHSize)
×
1990

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2119
                response, err = w.lockAndCreateFundingResponse(
2✔
2120
                        packet, addedOutpoints, changeIndex, customLockID,
2✔
2121
                        customLockDuration,
2✔
2122
                )
2✔
2123

2✔
2124
                return err
2✔
2125
        })
2126
        if err != nil {
2✔
2127
                return nil, err
×
2128
        }
×
2129

2130
        return response, nil
2✔
2131
}
2132

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

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

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

2159
                return nil
2✔
2160
        })
2161
}
2162

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

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

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

2186
        // Convert the lock leases to the RPC format.
2187
        rpcLocks := marshallLeases(locks)
2✔
2188

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

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

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

2✔
2208
                return changeIndex, nil
2✔
2209
        }
2✔
2210

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

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

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

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

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

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

×
2262
        return newChangeIndex, nil
×
2263
}
2264

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

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

2280
        return rpcLocks
2✔
2281
}
2282

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

2✔
2289
        switch changeAddressType {
2✔
2290
        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
2✔
2291
                return &waddrmgr.KeyScopeBIP0086
2✔
2292

2293
        default:
2✔
2294
                return nil
2✔
2295
        }
2296
}
2297

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

×
2303
        switch changeAddressType {
×
2304
        case chanfunding.P2TRChangeAddress:
×
2305
                return lnwallet.TaprootPubkey
×
2306

2307
        default:
×
2308
                return lnwallet.WitnessPubKey
×
2309
        }
2310
}
2311

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

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

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

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

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

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

2363
        return &SignPsbtResponse{
2✔
2364
                SignedPsbt:   signedPsbtBytes.Bytes(),
2✔
2365
                SignedInputs: signedInputs,
2✔
2366
        }, nil
2✔
2367
}
2368

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

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

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

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

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

2412
        var (
2✔
2413
                finalPsbtBytes bytes.Buffer
2✔
2414
                finalTxBytes   bytes.Buffer
2✔
2415
        )
2✔
2416

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

2431
        return &FinalizePsbtResponse{
2✔
2432
                SignedPsbt: finalPsbtBytes.Bytes(),
2✔
2433
                RawFinalTx: finalTxBytes.Bytes(),
2✔
2434
        }, nil
2✔
2435
}
2436

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

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

2452
                switch *account.AddrSchema {
2✔
2453
                case waddrmgr.KeyScopeBIP0049AddrSchema:
2✔
2454
                        addrType = AddressType_NESTED_WITNESS_PUBKEY_HASH
2✔
2455

2456
                case waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0049Plus]:
2✔
2457
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
2✔
2458

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

2464
        case waddrmgr.KeyScopeBIP0084:
2✔
2465
                addrType = AddressType_WITNESS_PUBKEY_HASH
2✔
2466

2467
        case waddrmgr.KeyScopeBIP0086:
2✔
2468
                addrType = AddressType_TAPROOT_PUBKEY
2✔
2469

2470
        case internalScope:
2✔
2471
                addrType = AddressType_WITNESS_PUBKEY_HASH
2✔
2472

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

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

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

2503
        return rpcAccount, nil
2✔
2504
}
2505

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

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

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

2534
        rpcAddressList := &AccountWithAddresses{
2✔
2535
                Name:           rpcAccount.Name,
2✔
2536
                AddressType:    rpcAccount.AddressType,
2✔
2537
                DerivationPath: rpcAccount.DerivationPath,
2✔
2538
                Addresses:      addresses,
2✔
2539
        }
2✔
2540

2✔
2541
        return rpcAddressList, nil
2✔
2542
}
2543

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

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

2556
        case AddressType_WITNESS_PUBKEY_HASH:
2✔
2557
                keyScope := waddrmgr.KeyScopeBIP0084
2✔
2558
                keyScopeFilter = &keyScope
2✔
2559

2560
        case AddressType_NESTED_WITNESS_PUBKEY_HASH,
2561
                AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
2✔
2562

2✔
2563
                keyScope := waddrmgr.KeyScopeBIP0049Plus
2✔
2564
                keyScopeFilter = &keyScope
2✔
2565

2566
        case AddressType_TAPROOT_PUBKEY:
2✔
2567
                keyScope := waddrmgr.KeyScopeBIP0086
2✔
2568
                keyScopeFilter = &keyScope
2✔
2569

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

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

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

2✔
2587
                        continue
2✔
2588
                }
2589

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

2599
        return &ListAccountsResponse{Accounts: rpcAccounts}, nil
2✔
2600
}
2601

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

2✔
2609
        numAnchorChans, err := w.cfg.CurrentNumAnchorChans()
2✔
2610
        if err != nil {
2✔
2611
                return nil, err
×
2612
        }
×
2613

2614
        additionalChans := req.AdditionalPublicChannels
2✔
2615
        totalChans := uint32(numAnchorChans) + additionalChans
2✔
2616
        reserved := w.cfg.Wallet.RequiredReserve(totalChans)
2✔
2617

2✔
2618
        return &RequiredReserveResponse{
2✔
2619
                RequiredReserve: int64(reserved),
2✔
2620
        }, nil
2✔
2621
}
2622

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

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

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

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

2654
                        return scopeI.Coin < scopeJ.Coin
×
2655
                }
2656

2657
                return scopeI.Purpose < scopeJ.Purpose
2✔
2658
        })
2659

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

2670
                rpcAddressLists = append(rpcAddressLists, rpcAddressList)
2✔
2671
        }
2672

2673
        return &ListAddressesResponse{
2✔
2674
                AccountWithAddresses: rpcAddressLists,
2✔
2675
        }, nil
2✔
2676
}
2677

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

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

2691
        case AddressType_WITNESS_PUBKEY_HASH:
2✔
2692
                addrTyp := waddrmgr.WitnessPubKey
2✔
2693
                return &addrTyp, nil
2✔
2694

2695
        case AddressType_NESTED_WITNESS_PUBKEY_HASH:
2✔
2696
                addrTyp := waddrmgr.NestedWitnessPubKey
2✔
2697
                return &addrTyp, nil
2✔
2698

2699
        case AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
2✔
2700
                addrTyp := waddrmgr.WitnessPubKey
2✔
2701
                return &addrTyp, nil
2✔
2702

2703
        case AddressType_TAPROOT_PUBKEY:
2✔
2704
                addrTyp := waddrmgr.TaprootPubKey
2✔
2705
                return &addrTyp, nil
2✔
2706

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

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

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

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

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

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

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

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

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

2764
        sigBytes := ecdsa.SignCompact(privKey, digest, pubKey.Compressed())
2✔
2765

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

2✔
2770
        return &SignMessageWithAddrResponse{
2✔
2771
                Signature: sig,
2✔
2772
        }, nil
2✔
2773
}
2774

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

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

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

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

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

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

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

2819
        var (
2✔
2820
                address    btcutil.Address
2✔
2821
                pubKeyHash = btcutil.Hash160(serializedPubkey)
2✔
2822
        )
2✔
2823

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

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

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

2851
                witnessScript, err := txscript.PayToAddrScript(address)
2✔
2852
                if err != nil {
2✔
2853
                        return nil, err
×
2854
                }
×
2855

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

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

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

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

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

2✔
2907
        accountPubKey, err := hdkeychain.NewKeyFromString(req.ExtendedPublicKey)
2✔
2908
        if err != nil {
2✔
2909
                return nil, err
×
2910
        }
×
2911

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

2925
        addrType, err := parseAddrType(req.AddressType, false)
2✔
2926
        if err != nil {
2✔
2927
                return nil, err
×
2928
        }
×
2929

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

2937
        rpcAccount, err := marshalWalletAccount(w.internalScope(), accountProps)
2✔
2938
        if err != nil {
2✔
2939
                return nil, err
×
2940
        }
×
2941

2942
        resp := &ImportAccountResponse{Account: rpcAccount}
2✔
2943
        if !req.DryRun {
4✔
2944
                return resp, nil
2✔
2945
        }
2✔
2946

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

2956
        return resp, nil
×
2957
}
2958

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

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

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

2984
        addrType, err := parseAddrType(req.AddressType, true)
2✔
2985
        if err != nil {
2✔
2986
                return nil, err
×
2987
        }
×
2988

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

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

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

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

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

3028
                tapscript = input.TapscriptFullTree(internalKey, leaves...)
2✔
3029

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

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

3048
                tapscript = input.TapscriptPartialReveal(
2✔
3049
                        internalKey, revealedLeaf,
2✔
3050
                        partialReveal.FullInclusionProof,
2✔
3051
                )
2✔
3052

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

3059
                tapscript = input.TapscriptRootHashOnly(internalKey, rootHash)
2✔
3060

3061
        case req.GetFullKeyOnly():
2✔
3062
                tapscript = input.TapscriptFullKeyOnly(internalKey)
2✔
3063

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

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

3075
        return &ImportTapscriptResponse{
2✔
3076
                P2TrAddress: addr.Address().String(),
2✔
3077
        }, nil
2✔
3078
}
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