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

lightningnetwork / lnd / 14519308938

17 Apr 2025 03:31PM UTC coverage: 58.586% (-10.5%) from 69.04%
14519308938

push

github

web-flow
Merge pull request #9724 from bhandras/fundpsbt-custom-input-lock

walletrpc: allow custom lock ID and duration in `FundPsbt`

34 of 41 new or added lines in 2 files covered. (82.93%)

28170 existing lines in 453 files now uncovered.

97185 of 165884 relevant lines covered (58.59%)

1.82 hits per line

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

66.81
/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) {
3✔
266
        // If the path of the wallet kit macaroon wasn't specified, then we'll
3✔
267
        // assume that it's found at the default network directory.
3✔
268
        if cfg.WalletKitMacPath == "" {
6✔
269
                cfg.WalletKitMacPath = filepath.Join(
3✔
270
                        cfg.NetworkDir, DefaultWalletKitMacFilename,
3✔
271
                )
3✔
272
        }
3✔
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
3✔
278
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
3✔
279
                !lnrpc.FileExists(macFilePath) {
6✔
280

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

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

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

3✔
309
        return walletKit, macPermissions, nil
3✔
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 {
3✔
316
        return nil
3✔
317
}
3✔
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 {
3✔
323
        return nil
3✔
324
}
3✔
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 {
3✔
331
        return SubServerName
3✔
332
}
3✔
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 {
3✔
340
        // We make sure that we register it with the main gRPC server to ensure
3✔
341
        // all our methods are routed properly.
3✔
342
        RegisterWalletKitServer(grpcServer, r)
3✔
343

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

3✔
347
        return nil
3✔
348
}
3✔
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 {
3✔
357

3✔
358
        // We make sure that we register it with the main REST server to ensure
3✔
359
        // all our methods are routed properly.
3✔
360
        err := RegisterWalletKitHandlerFromEndpoint(ctx, mux, dest, opts)
3✔
361
        if err != nil {
3✔
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 " +
3✔
368
                "root REST server")
3✔
369
        return nil
3✔
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) {
3✔
381

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

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

391
// internalScope returns the internal key scope.
392
func (w *WalletKit) internalScope() waddrmgr.KeyScope {
3✔
393
        return waddrmgr.KeyScope{
3✔
394
                Purpose: keychain.BIP0043Purpose,
3✔
395
                Coin:    w.cfg.ChainParams.HDCoinType,
3✔
396
        }
3✔
397
}
3✔
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) {
3✔
407

3✔
408
        // Force min_confs and max_confs to be zero if unconfirmed_only is
3✔
409
        // true.
3✔
410
        if req.UnconfirmedOnly && (req.MinConfs != 0 || req.MaxConfs != 0) {
3✔
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 {
6✔
419
                req.MaxConfs = math.MaxInt32
3✔
420
        }
3✔
421

422
        // Validate the confirmation arguments.
423
        minConfs, maxConfs, err := lnrpc.ParseConfs(req.MinConfs, req.MaxConfs)
3✔
424
        if err != nil {
3✔
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
3✔
435
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
6✔
436
                utxos, err = w.cfg.Wallet.ListUnspentWitness(
3✔
437
                        minConfs, maxConfs, req.Account,
3✔
438
                )
3✔
439

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

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

451
        return &ListUnspentResponse{
3✔
452
                Utxos: rpcUtxos,
3✔
453
        }, nil
3✔
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) {
3✔
548

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

554
        return &ListLeasesResponse{
3✔
555
                LockedUtxos: marshallLeases(leases),
3✔
556
        }, nil
3✔
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) {
3✔
564

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

572
        return &signrpc.KeyDescriptor{
3✔
573
                KeyLoc: &signrpc.KeyLocator{
3✔
574
                        KeyFamily: int32(nextKeyDesc.Family),
3✔
575
                        KeyIndex:  int32(nextKeyDesc.Index),
3✔
576
                },
3✔
577
                RawKeyBytes: nextKeyDesc.PubKey.SerializeCompressed(),
3✔
578
        }, nil
3✔
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) {
3✔
585

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

594
        return &signrpc.KeyDescriptor{
3✔
595
                KeyLoc: &signrpc.KeyLocator{
3✔
596
                        KeyFamily: int32(keyDesc.Family),
3✔
597
                        KeyIndex:  int32(keyDesc.Index),
3✔
598
                },
3✔
599
                RawKeyBytes: keyDesc.PubKey.SerializeCompressed(),
3✔
600
        }, nil
3✔
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) {
3✔
606

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

612
        addrType := lnwallet.WitnessPubKey
3✔
613
        switch req.Type {
3✔
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)
3✔
626
        if err != nil {
3✔
627
                return nil, err
×
628
        }
×
629

630
        return &AddrResponse{
3✔
631
                Addr: addr.String(),
3✔
632
        }, nil
3✔
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) {
3✔
638

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

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

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

655
        return lnrpc.RPCTransaction(res), nil
3✔
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) {
3✔
663

3✔
664
        switch {
3✔
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{}
3✔
673
        txReader := bytes.NewReader(req.TxHex)
3✔
674
        if err := tx.Deserialize(txReader); err != nil {
3✔
675
                return nil, err
×
676
        }
×
677

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

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

688
        return &PublishResponse{}, nil
3✔
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) {
3✔
703

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

710
        txHash, err := chainhash.NewHashFromStr(req.Txid)
3✔
711
        if err != nil {
3✔
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)
3✔
718
        if err != nil {
3✔
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 {
3✔
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{}
3✔
734
        txReader := bytes.NewReader(res.RawTx)
3✔
735
        if err := tx.Deserialize(txReader); err != nil {
3✔
736
                return nil, err
×
737
        }
×
738

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

744
        return &RemoveTransactionResponse{
3✔
745
                Status: "Successfully removed transaction",
3✔
746
        }, nil
3✔
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) {
3✔
754

3✔
755
        switch {
3✔
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
3✔
767
        outputsToCreate := make([]*wire.TxOut, 0, len(req.Outputs))
3✔
768
        for _, output := range req.Outputs {
6✔
769
                outputsToCreate = append(outputsToCreate, &wire.TxOut{
3✔
770
                        Value:    output.Value,
3✔
771
                        PkScript: output.PkScript,
3✔
772
                })
3✔
773
                totalOutputValue += output.Value
3✔
774
        }
3✔
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(
3✔
779
                req.MinConfs, req.SpendUnconfirmed,
3✔
780
        )
3✔
781
        if err != nil {
3✔
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(
3✔
789
                0, lnwallet.DefaultAccountName,
3✔
790
        )
3✔
791
        if err != nil {
3✔
792
                return nil, err
×
793
        }
×
794

795
        // We'll get the currently required reserve amount.
796
        reserve, err := w.RequiredReserve(ctx, &RequiredReserveRequest{})
3✔
797
        if err != nil {
3✔
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 {
6✔
804
                return nil, ErrInsufficientReserve
3✔
805
        }
3✔
806

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

812
        coinSelectionStrategy, err := lnrpc.UnmarshallCoinSelectionStrategy(
3✔
813
                req.CoinSelectionStrategy, w.cfg.CoinSelectionStrategy,
3✔
814
        )
3✔
815
        if err != nil {
3✔
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(
3✔
823
                nil, outputsToCreate, chainfee.SatPerKWeight(req.SatPerKw),
3✔
824
                minConfs, label, coinSelectionStrategy,
3✔
825
        )
3✔
826
        if err != nil {
3✔
827
                return nil, err
×
828
        }
×
829

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1018
        case in.Immediate:
3✔
1019
                immediate = in.Immediate
3✔
1020
        }
1021

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

1027
        return satPerKwOpt, immediate, nil
3✔
1028
}
1029

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

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

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

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

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

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

1071
                return params, ok, nil
3✔
1072
        }
1073

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

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

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

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

1098
        startingFeeRate := inp.Params.StartingFeeRate
3✔
1099

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

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

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

3✔
1120
        return params, ok, nil
3✔
1121
}
1122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1416
        return nil
3✔
1417
}
1418

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1615
        var customLockDuration time.Duration
3✔
1616
        if req.LockExpirationSeconds != 0 {
6✔
1617
                customLockDuration = time.Duration(req.LockExpirationSeconds) *
3✔
1618
                        time.Second
3✔
1619
        }
3✔
1620

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

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

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

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

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

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

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

1682
                        changeIndex = t.ExistingOutputIndex
3✔
1683

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

1691
                        changeType = chanfunding.ExistingChangeAddress
3✔
1692

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

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

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

1712
                maxFeeRatio := chanfunding.DefaultMaxFeeRatio
3✔
1713

3✔
1714
                if req.MaxFeeRatio != 0 {
3✔
1715
                        maxFeeRatio = req.MaxFeeRatio
×
1716
                }
×
1717

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1832
                                        return false
3✔
1833
                                }
3✔
1834

1835
                                return true
×
1836
                        }
1837

1838
                        eligibleUtxos := fn.Filter(utxos, filterFn)
3✔
1839

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

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

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

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

1881
                        return allowed
3✔
1882
                }
1883

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

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

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

3✔
1914
                return err
3✔
1915
        })
1916
        if err != nil {
6✔
1917
                return nil, err
3✔
1918
        }
3✔
1919

1920
        return response, nil
3✔
1921
}
1922

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2131
        return response, nil
3✔
2132
}
2133

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

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

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

2160
                return nil
3✔
2161
        })
2162
}
2163

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

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

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

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

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

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

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

3✔
2209
                return changeIndex, nil
3✔
2210
        }
3✔
2211

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

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

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

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

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

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

×
2263
        return newChangeIndex, nil
×
2264
}
2265

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

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

2281
        return rpcLocks
3✔
2282
}
2283

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

3✔
2290
        switch changeAddressType {
3✔
2291
        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
3✔
2292
                return &waddrmgr.KeyScopeBIP0086
3✔
2293

2294
        default:
3✔
2295
                return nil
3✔
2296
        }
2297
}
2298

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2413
        var (
3✔
2414
                finalPsbtBytes bytes.Buffer
3✔
2415
                finalTxBytes   bytes.Buffer
3✔
2416
        )
3✔
2417

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

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

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

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

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

2457
                case waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0049Plus]:
3✔
2458
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
3✔
2459

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

2465
        case waddrmgr.KeyScopeBIP0084:
3✔
2466
                addrType = AddressType_WITNESS_PUBKEY_HASH
3✔
2467

2468
        case waddrmgr.KeyScopeBIP0086:
3✔
2469
                addrType = AddressType_TAPROOT_PUBKEY
3✔
2470

2471
        case internalScope:
3✔
2472
                addrType = AddressType_WITNESS_PUBKEY_HASH
3✔
2473

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

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

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

2504
        return rpcAccount, nil
3✔
2505
}
2506

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

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

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

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

3✔
2542
        return rpcAddressList, nil
3✔
2543
}
2544

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

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

2557
        case AddressType_WITNESS_PUBKEY_HASH:
3✔
2558
                keyScope := waddrmgr.KeyScopeBIP0084
3✔
2559
                keyScopeFilter = &keyScope
3✔
2560

2561
        case AddressType_NESTED_WITNESS_PUBKEY_HASH,
2562
                AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
3✔
2563

3✔
2564
                keyScope := waddrmgr.KeyScopeBIP0049Plus
3✔
2565
                keyScopeFilter = &keyScope
3✔
2566

2567
        case AddressType_TAPROOT_PUBKEY:
3✔
2568
                keyScope := waddrmgr.KeyScopeBIP0086
3✔
2569
                keyScopeFilter = &keyScope
3✔
2570

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

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

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

3✔
2588
                        continue
3✔
2589
                }
2590

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

2600
        return &ListAccountsResponse{Accounts: rpcAccounts}, nil
3✔
2601
}
2602

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

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

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

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

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

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

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

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

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

2658
                return scopeI.Purpose < scopeJ.Purpose
3✔
2659
        })
2660

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

2671
                rpcAddressLists = append(rpcAddressLists, rpcAddressList)
3✔
2672
        }
2673

2674
        return &ListAddressesResponse{
3✔
2675
                AccountWithAddresses: rpcAddressLists,
3✔
2676
        }, nil
3✔
2677
}
2678

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2765
        sigBytes := ecdsa.SignCompact(privKey, digest, pubKey.Compressed())
3✔
2766

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

3✔
2771
        return &SignMessageWithAddrResponse{
3✔
2772
                Signature: sig,
3✔
2773
        }, nil
3✔
2774
}
2775

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2943
        resp := &ImportAccountResponse{Account: rpcAccount}
3✔
2944
        if !req.DryRun {
6✔
2945
                return resp, nil
3✔
2946
        }
3✔
2947

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

2957
        return resp, nil
×
2958
}
2959

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

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

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

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

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

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

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

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

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

3029
                tapscript = input.TapscriptFullTree(internalKey, leaves...)
3✔
3030

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

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

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

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

3060
                tapscript = input.TapscriptRootHashOnly(internalKey, rootHash)
3✔
3061

3062
        case req.GetFullKeyOnly():
3✔
3063
                tapscript = input.TapscriptFullKeyOnly(internalKey)
3✔
3064

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

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

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