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

lightningnetwork / lnd / 12412879685

19 Dec 2024 12:40PM UTC coverage: 58.744% (+0.09%) from 58.653%
12412879685

Pull #8754

github

ViktorTigerstrom
itest: wrap deriveCustomScopeAccounts at 80 chars

This commit fixes that word wrapping for the deriveCustomScopeAccounts
function docs, and ensures that it wraps at 80 characters or less.
Pull Request #8754: Add `Outbound` Remote Signer implementation

1858 of 2816 new or added lines in 47 files covered. (65.98%)

267 existing lines in 51 files now uncovered.

136038 of 231578 relevant lines covered (58.74%)

19020.65 hits per line

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

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

4
package walletrpc
5

6
import (
7
        "bytes"
8
        "context"
9
        "encoding/base64"
10
        "encoding/binary"
11
        "errors"
12
        "fmt"
13
        "math"
14
        "os"
15
        "path/filepath"
16
        "sort"
17
        "sync"
18
        "sync/atomic"
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
        "golang.org/x/exp/maps"
49
        "google.golang.org/grpc"
50
        "gopkg.in/macaroon-bakery.v2/bakery"
51
)
52

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

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

195
        // DefaultWalletKitMacFilename is the default name of the wallet kit
196
        // macaroon that we expect to find via a file handle within the main
197
        // configuration file in this package.
198
        DefaultWalletKitMacFilename = "walletkit.macaroon"
199

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

248
// InboundRemoteSignerConnection is an interface that mimics a subset of the
249
// rpcwallet InboundRemoteSignerConnection interface to avoid circular
250
// dependencies.
251
type InboundRemoteSignerConnection interface {
252
        // AddConnection feeds the inbound connection handler with the incoming
253
        // stream set up by an outbound remote signer and then blocks until the
254
        // stream is closed. Lnd can then send any requests to the remote signer
255
        // through the stream.
256
        AddConnection(stream WalletKit_SignCoordinatorStreamsServer) error
257
}
258

259
// ServerShell is a shell struct holding a reference to the actual sub-server.
260
// It is used to register the gRPC sub-server with the root server before we
261
// have the necessary dependencies to populate the actual sub-server.
262
type ServerShell struct {
263
        WalletKitServer
264
}
265

266
// WalletKit is a sub-RPC server that exposes a tool kit which allows clients
267
// to execute common wallet operations. This includes requesting new addresses,
268
// keys (for contracts!), and publishing transactions.
269
type WalletKit struct {
270
        injected int32 // To be used atomically.
271

272
        // Required by the grpc-gateway/v2 library for forward compatibility.
273
        UnimplementedWalletKitServer
274

275
        cfg *Config
276

277
        // As we allow rpc requests into the server before dependencies have
278
        // been finalized, the read lock should be held in functions that
279
        // accesses values from the cfg before dependencies are finalized.
280
        // The write lock should be held when setting the cfg.
281
        sync.RWMutex
282
}
283

284
// A compile time check to ensure that WalletKit fully implements the
285
// WalletKitServer gRPC service.
286
var _ WalletKitServer = (*WalletKit)(nil)
287

288
// New creates a new instance of the WalletKit sub-RPC server.
289
func New() (*WalletKit, lnrpc.MacaroonPerms, error) {
3✔
290
        return &WalletKit{cfg: &Config{}}, macPermissions, nil
3✔
291
}
3✔
292

293
// Stop signals any active goroutines for a graceful closure.
294
//
295
// NOTE: This is part of the lnrpc.SubServer interface.
296
func (w *WalletKit) Stop() error {
3✔
297
        return nil
3✔
298
}
3✔
299

300
// InjectDependencies populates the sub-server's dependencies. If the
301
// finalizeDependencies boolean is true, then the sub-server will finalize its
302
// dependencies and return an error if any required dependencies are missing.
303
//
304
// NOTE: This is part of the lnrpc.SubServer interface.
305
func (w *WalletKit) InjectDependencies(
306
        configRegistry lnrpc.SubServerConfigDispatcher,
307
        finalizeDependencies bool) error {
3✔
308

3✔
309
        if finalizeDependencies && atomic.AddInt32(&w.injected, 1) != 1 {
3✔
NEW
310
                return lnrpc.ErrDependenciesFinalized
×
NEW
311
        }
×
312

313
        w.Lock()
3✔
314
        defer w.Unlock()
3✔
315

3✔
316
        cfg, err := getConfig(configRegistry, finalizeDependencies)
3✔
317
        if err != nil {
3✔
NEW
318
                return err
×
NEW
319
        }
×
320

321
        if finalizeDependencies {
6✔
322
                w.cfg = cfg
3✔
323

3✔
324
                return nil
3✔
325
        }
3✔
326

327
        // If the path of the wallet kit macaroon wasn't specified, then we'll
328
        // assume that it's found at the default network directory.
329
        if cfg.WalletKitMacPath == "" {
6✔
330
                cfg.WalletKitMacPath = filepath.Join(
3✔
331
                        cfg.NetworkDir, DefaultWalletKitMacFilename,
3✔
332
                )
3✔
333
        }
3✔
334

335
        // Now that we know the full path of the wallet kit macaroon, we can
336
        // check to see if we need to create it or not. If stateless_init is set
337
        // then we don't write the macaroons.
338
        macFilePath := cfg.WalletKitMacPath
3✔
339
        if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
3✔
340
                !lnrpc.FileExists(macFilePath) {
3✔
UNCOV
341

×
UNCOV
342
                log.Infof("Baking macaroons for WalletKit RPC Server at: %v",
×
UNCOV
343
                        macFilePath)
×
UNCOV
344

×
UNCOV
345
                // At this point, we know that the wallet kit macaroon doesn't
×
UNCOV
346
                // yet, exist, so we need to create it with the help of the
×
UNCOV
347
                // main macaroon service.
×
UNCOV
348
                walletKitMac, err := cfg.MacService.NewMacaroon(
×
UNCOV
349
                        context.Background(), macaroons.DefaultRootKeyID,
×
UNCOV
350
                        macaroonOps...,
×
UNCOV
351
                )
×
UNCOV
352
                if err != nil {
×
NEW
353
                        return err
×
354
                }
×
UNCOV
355
                walletKitMacBytes, err := walletKitMac.M().MarshalBinary()
×
UNCOV
356
                if err != nil {
×
NEW
357
                        return err
×
358
                }
×
UNCOV
359
                err = os.WriteFile(macFilePath, walletKitMacBytes, 0644)
×
UNCOV
360
                if err != nil {
×
361
                        _ = os.Remove(macFilePath)
×
NEW
362
                        return err
×
363
                }
×
364
        }
365

366
        w.cfg = cfg
3✔
367

3✔
368
        return nil
3✔
369
}
370

371
// Name returns a unique string representation of the sub-server. This can be
372
// used to identify the sub-server and also de-duplicate them.
373
//
374
// NOTE: This is part of the lnrpc.SubServer interface.
375
func (w *WalletKit) Name() string {
3✔
376
        return SubServerName
3✔
377
}
3✔
378

379
// RegisterWithRootServer will be called by the root gRPC server to direct a
380
// sub RPC server to register itself with the main gRPC root server. Until this
381
// is called, each sub-server won't be able to have requests routed towards it.
382
//
383
// NOTE: This is part of the lnrpc.GrpcHandler interface.
384
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
3✔
385
        // We make sure that we register it with the main gRPC server to ensure
3✔
386
        // all our methods are routed properly.
3✔
387
        RegisterWalletKitServer(grpcServer, r)
3✔
388

3✔
389
        log.Debugf("WalletKit RPC server successfully registered with " +
3✔
390
                "root gRPC server")
3✔
391

3✔
392
        return nil
3✔
393
}
3✔
394

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

3✔
403
        // We make sure that we register it with the main REST server to ensure
3✔
404
        // all our methods are routed properly.
3✔
405
        err := RegisterWalletKitHandlerFromEndpoint(ctx, mux, dest, opts)
3✔
406
        if err != nil {
3✔
407
                log.Errorf("Could not register WalletKit REST server "+
×
408
                        "with root REST server: %v", err)
×
409
                return err
×
410
        }
×
411

412
        log.Debugf("WalletKit REST server successfully registered with " +
3✔
413
                "root REST server")
3✔
414
        return nil
3✔
415
}
416

417
// CreateSubServer creates an instance of the sub-server, and returns the
418
// macaroon permissions that the sub-server wishes to pass on to the root server
419
// for all methods routed towards it.
420
//
421
// NOTE: This is part of the lnrpc.GrpcHandler interface.
422
func (r *ServerShell) CreateSubServer() (
423
        lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
3✔
424

3✔
425
        subServer, macPermissions, err := New()
3✔
426
        if err != nil {
3✔
427
                return nil, nil, err
×
428
        }
×
429

430
        r.WalletKitServer = subServer
3✔
431
        return subServer, macPermissions, nil
3✔
432
}
433

434
// internalScope returns the internal key scope.
435
func (w *WalletKit) internalScope() waddrmgr.KeyScope {
3✔
436
        return waddrmgr.KeyScope{
3✔
437
                Purpose: keychain.BIP0043Purpose,
3✔
438
                Coin:    w.cfg.ChainParams.HDCoinType,
3✔
439
        }
3✔
440
}
3✔
441

442
// ListUnspent returns useful information about each unspent output owned by
443
// the wallet, as reported by the underlying `ListUnspentWitness`; the
444
// information returned is: outpoint, amount in satoshis, address, address
445
// type, scriptPubKey in hex and number of confirmations. The result is
446
// filtered to contain outputs whose number of confirmations is between a
447
// minimum and maximum number of confirmations specified by the user.
448
func (w *WalletKit) ListUnspent(ctx context.Context,
449
        req *ListUnspentRequest) (*ListUnspentResponse, error) {
3✔
450

3✔
451
        // Force min_confs and max_confs to be zero if unconfirmed_only is
3✔
452
        // true.
3✔
453
        if req.UnconfirmedOnly && (req.MinConfs != 0 || req.MaxConfs != 0) {
3✔
454
                return nil, fmt.Errorf("min_confs and max_confs must be zero " +
×
455
                        "if unconfirmed_only is true")
×
456
        }
×
457

458
        // When unconfirmed_only is inactive and max_confs is zero (default
459
        // values), we will override max_confs to be a MaxInt32, in order
460
        // to return all confirmed and unconfirmed utxos as a default response.
461
        if req.MaxConfs == 0 && !req.UnconfirmedOnly {
6✔
462
                req.MaxConfs = math.MaxInt32
3✔
463
        }
3✔
464

465
        // Validate the confirmation arguments.
466
        minConfs, maxConfs, err := lnrpc.ParseConfs(req.MinConfs, req.MaxConfs)
3✔
467
        if err != nil {
3✔
468
                return nil, err
×
469
        }
×
470

471
        // With our arguments validated, we'll query the internal wallet for
472
        // the set of UTXOs that match our query.
473
        //
474
        // We'll acquire the global coin selection lock to ensure there aren't
475
        // any other concurrent processes attempting to lock any UTXOs which may
476
        // be shown available to us.
477
        var utxos []*lnwallet.Utxo
3✔
478

3✔
479
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
6✔
480
                utxos, err = w.cfg.Wallet.ListUnspentWitness(
3✔
481
                        minConfs, maxConfs, req.Account,
3✔
482
                )
3✔
483

3✔
484
                return err
3✔
485
        })
3✔
486
        if err != nil {
3✔
487
                return nil, err
×
488
        }
×
489

490
        rpcUtxos, err := lnrpc.MarshalUtxos(utxos, w.cfg.ChainParams)
3✔
491
        if err != nil {
3✔
492
                return nil, err
×
493
        }
×
494

495
        return &ListUnspentResponse{
3✔
496
                Utxos: rpcUtxos,
3✔
497
        }, nil
3✔
498
}
499

500
// SignCoordinatorStreams opens a bi-directional streaming RPC, which is used
501
// to allow a remote signer to process sign requests on behalf of the wallet.
502
func (w *WalletKit) SignCoordinatorStreams(
503
        stream WalletKit_SignCoordinatorStreamsServer) error {
3✔
504

3✔
505
        w.RLock()
3✔
506

3✔
507
        // Check that the user actually has configured that the reverse remote
3✔
508
        // signer functionality should be enabled.
3✔
509
        if w.cfg.RemoteSignerConnection == nil {
3✔
NEW
510
                w.RUnlock()
×
NEW
511

×
NEW
512
                return fmt.Errorf("inbound connections from remote signers " +
×
NEW
513
                        "not enabled in config")
×
NEW
514
        }
×
515

516
        connectionCoordinator := w.cfg.RemoteSignerConnection
3✔
517

3✔
518
        // Release the read lock as we will acquire the write in the
3✔
519
        // InjectDependencies function while the stream is still open.
3✔
520
        w.RUnlock()
3✔
521

3✔
522
        return connectionCoordinator.AddConnection(stream)
3✔
523
}
524

525
// LeaseOutput locks an output to the given ID, preventing it from being
526
// available for any future coin selection attempts. The absolute time of the
527
// lock's expiration is returned. The expiration of the lock can be extended by
528
// successive invocations of this call. Outputs can be unlocked before their
529
// expiration through `ReleaseOutput`.
530
//
531
// If the output is not known, wtxmgr.ErrUnknownOutput is returned. If the
532
// output has already been locked to a different ID, then
533
// wtxmgr.ErrOutputAlreadyLocked is returned.
534
func (w *WalletKit) LeaseOutput(ctx context.Context,
535
        req *LeaseOutputRequest) (*LeaseOutputResponse, error) {
×
536

×
537
        if len(req.Id) != 32 {
×
538
                return nil, errors.New("id must be 32 random bytes")
×
539
        }
×
540
        var lockID wtxmgr.LockID
×
541
        copy(lockID[:], req.Id)
×
542

×
543
        // Don't allow ID's of 32 bytes, but all zeros.
×
544
        if lockID == (wtxmgr.LockID{}) {
×
545
                return nil, errors.New("id must be 32 random bytes")
×
546
        }
×
547

548
        // Don't allow our internal ID to be used externally for locking. Only
549
        // unlocking is allowed.
550
        if lockID == chanfunding.LndInternalLockID {
×
551
                return nil, errors.New("reserved id cannot be used")
×
552
        }
×
553

554
        op, err := UnmarshallOutPoint(req.Outpoint)
×
555
        if err != nil {
×
556
                return nil, err
×
557
        }
×
558

559
        // Use the specified lock duration or fall back to the default.
560
        duration := chanfunding.DefaultLockDuration
×
561
        if req.ExpirationSeconds != 0 {
×
562
                duration = time.Duration(req.ExpirationSeconds) * time.Second
×
563
        }
×
564

565
        // Acquire the global coin selection lock to ensure there aren't any
566
        // other concurrent processes attempting to lease the same UTXO.
567
        var expiration time.Time
×
568
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
×
569
                expiration, err = w.cfg.Wallet.LeaseOutput(
×
570
                        lockID, *op, duration,
×
571
                )
×
572
                return err
×
573
        })
×
574
        if err != nil {
×
575
                return nil, err
×
576
        }
×
577

578
        return &LeaseOutputResponse{
×
579
                Expiration: uint64(expiration.Unix()),
×
580
        }, nil
×
581
}
582

583
// ReleaseOutput unlocks an output, allowing it to be available for coin
584
// selection if it remains unspent. The ID should match the one used to
585
// originally lock the output.
586
func (w *WalletKit) ReleaseOutput(ctx context.Context,
587
        req *ReleaseOutputRequest) (*ReleaseOutputResponse, error) {
×
588

×
589
        if len(req.Id) != 32 {
×
590
                return nil, errors.New("id must be 32 random bytes")
×
591
        }
×
592
        var lockID wtxmgr.LockID
×
593
        copy(lockID[:], req.Id)
×
594

×
595
        op, err := UnmarshallOutPoint(req.Outpoint)
×
596
        if err != nil {
×
597
                return nil, err
×
598
        }
×
599

600
        // Acquire the global coin selection lock to maintain consistency as
601
        // it's acquired when we initially leased the output.
602
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
×
603
                return w.cfg.Wallet.ReleaseOutput(lockID, *op)
×
604
        })
×
605
        if err != nil {
×
606
                return nil, err
×
607
        }
×
608

609
        return &ReleaseOutputResponse{
×
610
                Status: fmt.Sprintf("output %v released", op.String()),
×
611
        }, nil
×
612
}
613

614
// ListLeases returns a list of all currently locked utxos.
615
func (w *WalletKit) ListLeases(ctx context.Context,
616
        req *ListLeasesRequest) (*ListLeasesResponse, error) {
×
617

×
618
        leases, err := w.cfg.Wallet.ListLeasedOutputs()
×
619
        if err != nil {
×
620
                return nil, err
×
621
        }
×
622

623
        return &ListLeasesResponse{
×
624
                LockedUtxos: marshallLeases(leases),
×
625
        }, nil
×
626
}
627

628
// DeriveNextKey attempts to derive the *next* key within the key family
629
// (account in BIP43) specified. This method should return the next external
630
// child within this branch.
631
func (w *WalletKit) DeriveNextKey(ctx context.Context,
632
        req *KeyReq) (*signrpc.KeyDescriptor, error) {
3✔
633

3✔
634
        nextKeyDesc, err := w.cfg.KeyRing.DeriveNextKey(
3✔
635
                keychain.KeyFamily(req.KeyFamily),
3✔
636
        )
3✔
637
        if err != nil {
3✔
638
                return nil, err
×
639
        }
×
640

641
        return &signrpc.KeyDescriptor{
3✔
642
                KeyLoc: &signrpc.KeyLocator{
3✔
643
                        KeyFamily: int32(nextKeyDesc.Family),
3✔
644
                        KeyIndex:  int32(nextKeyDesc.Index),
3✔
645
                },
3✔
646
                RawKeyBytes: nextKeyDesc.PubKey.SerializeCompressed(),
3✔
647
        }, nil
3✔
648
}
649

650
// DeriveKey attempts to derive an arbitrary key specified by the passed
651
// KeyLocator.
652
func (w *WalletKit) DeriveKey(ctx context.Context,
653
        req *signrpc.KeyLocator) (*signrpc.KeyDescriptor, error) {
3✔
654

3✔
655
        keyDesc, err := w.cfg.KeyRing.DeriveKey(keychain.KeyLocator{
3✔
656
                Family: keychain.KeyFamily(req.KeyFamily),
3✔
657
                Index:  uint32(req.KeyIndex),
3✔
658
        })
3✔
659
        if err != nil {
3✔
660
                return nil, err
×
661
        }
×
662

663
        return &signrpc.KeyDescriptor{
3✔
664
                KeyLoc: &signrpc.KeyLocator{
3✔
665
                        KeyFamily: int32(keyDesc.Family),
3✔
666
                        KeyIndex:  int32(keyDesc.Index),
3✔
667
                },
3✔
668
                RawKeyBytes: keyDesc.PubKey.SerializeCompressed(),
3✔
669
        }, nil
3✔
670
}
671

672
// NextAddr returns the next unused address within the wallet.
673
func (w *WalletKit) NextAddr(ctx context.Context,
674
        req *AddrRequest) (*AddrResponse, error) {
3✔
675

3✔
676
        account := lnwallet.DefaultAccountName
3✔
677
        if req.Account != "" {
3✔
678
                account = req.Account
×
679
        }
×
680

681
        addrType := lnwallet.WitnessPubKey
3✔
682
        switch req.Type {
3✔
683
        case AddressType_NESTED_WITNESS_PUBKEY_HASH:
×
684
                addrType = lnwallet.NestedWitnessPubKey
×
685

686
        case AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
×
687
                return nil, fmt.Errorf("invalid address type for next "+
×
688
                        "address: %v", req.Type)
×
689

690
        case AddressType_TAPROOT_PUBKEY:
×
691
                addrType = lnwallet.TaprootPubkey
×
692
        }
693

694
        addr, err := w.cfg.Wallet.NewAddress(addrType, req.Change, account)
3✔
695
        if err != nil {
3✔
696
                return nil, err
×
697
        }
×
698

699
        return &AddrResponse{
3✔
700
                Addr: addr.String(),
3✔
701
        }, nil
3✔
702
}
703

704
// GetTransaction returns a transaction from the wallet given its hash.
705
func (w *WalletKit) GetTransaction(_ context.Context,
706
        req *GetTransactionRequest) (*lnrpc.Transaction, error) {
3✔
707

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

714
        txHash, err := chainhash.NewHashFromStr(req.Txid)
3✔
715
        if err != nil {
3✔
716
                return nil, err
×
717
        }
×
718

719
        res, err := w.cfg.Wallet.GetTransactionDetails(txHash)
3✔
720
        if err != nil {
3✔
721
                return nil, err
×
722
        }
×
723

724
        return lnrpc.RPCTransaction(res), nil
3✔
725
}
726

727
// Attempts to publish the passed transaction to the network. Once this returns
728
// without an error, the wallet will continually attempt to re-broadcast the
729
// transaction on start up, until it enters the chain.
730
func (w *WalletKit) PublishTransaction(ctx context.Context,
731
        req *Transaction) (*PublishResponse, error) {
3✔
732

3✔
733
        switch {
3✔
734
        // If the client doesn't specify a transaction, then there's nothing to
735
        // publish.
736
        case len(req.TxHex) == 0:
×
737
                return nil, fmt.Errorf("must provide a transaction to " +
×
738
                        "publish")
×
739
        }
740

741
        tx := &wire.MsgTx{}
3✔
742
        txReader := bytes.NewReader(req.TxHex)
3✔
743
        if err := tx.Deserialize(txReader); err != nil {
3✔
744
                return nil, err
×
745
        }
×
746

747
        label, err := labels.ValidateAPI(req.Label)
3✔
748
        if err != nil {
3✔
749
                return nil, err
×
750
        }
×
751

752
        err = w.cfg.Wallet.PublishTransaction(tx, label)
3✔
753
        if err != nil {
3✔
754
                return nil, err
×
755
        }
×
756

757
        return &PublishResponse{}, nil
3✔
758
}
759

760
// RemoveTransaction attempts to remove the transaction and all of its
761
// descendants resulting from further spends of the outputs of the provided
762
// transaction id.
763
// NOTE: We do not remove the transaction from the rebroadcaster which might
764
// run in the background rebroadcasting not yet confirmed transactions. We do
765
// not have access to the rebroadcaster here nor should we. This command is not
766
// a way to remove transactions from the network. It is a way to shortcircuit
767
// wallet utxo housekeeping while transactions are still unconfirmed and we know
768
// that a transaction will never confirm because a replacement already pays
769
// higher fees.
770
func (w *WalletKit) RemoveTransaction(_ context.Context,
771
        req *GetTransactionRequest) (*RemoveTransactionResponse, error) {
3✔
772

3✔
773
        // If the client doesn't specify a hash, then there's nothing to
3✔
774
        // return.
3✔
775
        if req.Txid == "" {
3✔
776
                return nil, fmt.Errorf("must provide a transaction hash")
×
777
        }
×
778

779
        txHash, err := chainhash.NewHashFromStr(req.Txid)
3✔
780
        if err != nil {
3✔
781
                return nil, err
×
782
        }
×
783

784
        // Query the tx store of our internal wallet for the specified
785
        // transaction.
786
        res, err := w.cfg.Wallet.GetTransactionDetails(txHash)
3✔
787
        if err != nil {
3✔
788
                return nil, fmt.Errorf("transaction with txid=%v not found "+
×
789
                        "in the internal wallet store", txHash)
×
790
        }
×
791

792
        // Only allow unconfirmed transactions to be removed because as soon
793
        // as a transaction is confirmed it will be evaluated by the wallet
794
        // again and the wallet state would be updated in case the user had
795
        // removed the transaction accidentally.
796
        if res.NumConfirmations > 0 {
3✔
797
                return nil, fmt.Errorf("transaction with txid=%v is already "+
×
798
                        "confirmed (numConfs=%d) cannot be removed", txHash,
×
799
                        res.NumConfirmations)
×
800
        }
×
801

802
        tx := &wire.MsgTx{}
3✔
803
        txReader := bytes.NewReader(res.RawTx)
3✔
804
        if err := tx.Deserialize(txReader); err != nil {
3✔
805
                return nil, err
×
806
        }
×
807

808
        err = w.cfg.Wallet.RemoveDescendants(tx)
3✔
809
        if err != nil {
3✔
810
                return nil, err
×
811
        }
×
812

813
        return &RemoveTransactionResponse{
3✔
814
                Status: "Successfully removed transaction",
3✔
815
        }, nil
3✔
816
}
817

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

3✔
824
        switch {
3✔
825
        // If the client didn't specify any outputs to create, then  we can't
826
        // proceed .
827
        case len(req.Outputs) == 0:
×
828
                return nil, fmt.Errorf("must specify at least one output " +
×
829
                        "to create")
×
830
        }
831

832
        // Before we can request this transaction to be created, we'll need to
833
        // amp the protos back into the format that the internal wallet will
834
        // recognize.
835
        var totalOutputValue int64
3✔
836
        outputsToCreate := make([]*wire.TxOut, 0, len(req.Outputs))
3✔
837
        for _, output := range req.Outputs {
6✔
838
                outputsToCreate = append(outputsToCreate, &wire.TxOut{
3✔
839
                        Value:    output.Value,
3✔
840
                        PkScript: output.PkScript,
3✔
841
                })
3✔
842
                totalOutputValue += output.Value
3✔
843
        }
3✔
844

845
        // Then, we'll extract the minimum number of confirmations that each
846
        // output we use to fund the transaction should satisfy.
847
        minConfs, err := lnrpc.ExtractMinConfs(
3✔
848
                req.MinConfs, req.SpendUnconfirmed,
3✔
849
        )
3✔
850
        if err != nil {
3✔
851
                return nil, err
×
852
        }
×
853

854
        // Before sending out funds we need to ensure that the remainder of our
855
        // wallet funds would cover for the anchor reserve requirement. We'll
856
        // also take unconfirmed funds into account.
857
        walletBalance, err := w.cfg.Wallet.ConfirmedBalance(
3✔
858
                0, lnwallet.DefaultAccountName,
3✔
859
        )
3✔
860
        if err != nil {
3✔
861
                return nil, err
×
862
        }
×
863

864
        // We'll get the currently required reserve amount.
865
        reserve, err := w.RequiredReserve(ctx, &RequiredReserveRequest{})
3✔
866
        if err != nil {
3✔
867
                return nil, err
×
868
        }
×
869

870
        // Then we check if our current wallet balance undershoots the required
871
        // reserve if we'd send out the outputs specified in the request.
872
        if int64(walletBalance)-totalOutputValue < reserve.RequiredReserve {
6✔
873
                return nil, ErrInsufficientReserve
3✔
874
        }
3✔
875

876
        label, err := labels.ValidateAPI(req.Label)
3✔
877
        if err != nil {
3✔
878
                return nil, err
×
879
        }
×
880

881
        coinSelectionStrategy, err := lnrpc.UnmarshallCoinSelectionStrategy(
3✔
882
                req.CoinSelectionStrategy, w.cfg.CoinSelectionStrategy,
3✔
883
        )
3✔
884
        if err != nil {
3✔
885
                return nil, err
×
886
        }
×
887

888
        // Now that we have the outputs mapped and checked for the reserve
889
        // requirement, we can request that the wallet attempts to create this
890
        // transaction.
891
        tx, err := w.cfg.Wallet.SendOutputs(
3✔
892
                nil, outputsToCreate, chainfee.SatPerKWeight(req.SatPerKw),
3✔
893
                minConfs, label, coinSelectionStrategy,
3✔
894
        )
3✔
895
        if err != nil {
3✔
896
                return nil, err
×
897
        }
×
898

899
        var b bytes.Buffer
3✔
900
        if err := tx.Serialize(&b); err != nil {
3✔
901
                return nil, err
×
902
        }
×
903

904
        return &SendOutputsResponse{
3✔
905
                RawTx: b.Bytes(),
3✔
906
        }, nil
3✔
907
}
908

909
// EstimateFee attempts to query the internal fee estimator of the wallet to
910
// determine the fee (in sat/kw) to attach to a transaction in order to achieve
911
// the confirmation target.
912
func (w *WalletKit) EstimateFee(ctx context.Context,
913
        req *EstimateFeeRequest) (*EstimateFeeResponse, error) {
×
914

×
915
        switch {
×
916
        // A confirmation target of zero doesn't make any sense. Similarly, we
917
        // reject confirmation targets of 1 as they're unreasonable.
918
        case req.ConfTarget == 0 || req.ConfTarget == 1:
×
919
                return nil, fmt.Errorf("confirmation target must be greater " +
×
920
                        "than 1")
×
921
        }
922

923
        satPerKw, err := w.cfg.FeeEstimator.EstimateFeePerKW(
×
924
                uint32(req.ConfTarget),
×
925
        )
×
926
        if err != nil {
×
927
                return nil, err
×
928
        }
×
929

930
        relayFeePerKw := w.cfg.FeeEstimator.RelayFeePerKW()
×
931

×
932
        return &EstimateFeeResponse{
×
933
                SatPerKw:            int64(satPerKw),
×
934
                MinRelayFeeSatPerKw: int64(relayFeePerKw),
×
935
        }, nil
×
936
}
937

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

3✔
946
        // Retrieve all of the outputs the UtxoSweeper is currently trying to
3✔
947
        // sweep.
3✔
948
        inputsMap, err := w.cfg.Sweeper.PendingInputs()
3✔
949
        if err != nil {
3✔
950
                return nil, err
×
951
        }
×
952

953
        // Convert them into their respective RPC format.
954
        rpcPendingSweeps := make([]*PendingSweep, 0, len(inputsMap))
3✔
955
        for _, inp := range inputsMap {
6✔
956
                witnessType, ok := allWitnessTypes[inp.WitnessType]
3✔
957
                if !ok {
3✔
958
                        return nil, fmt.Errorf("unhandled witness type %v for "+
×
959
                                "input %v", inp.WitnessType, inp.OutPoint)
×
960
                }
×
961

962
                op := lnrpc.MarshalOutPoint(&inp.OutPoint)
3✔
963
                amountSat := uint32(inp.Amount)
3✔
964
                satPerVbyte := uint64(inp.LastFeeRate.FeePerVByte())
3✔
965
                broadcastAttempts := uint32(inp.BroadcastAttempts)
3✔
966

3✔
967
                // Get the requested starting fee rate, if set.
3✔
968
                startingFeeRate := fn.MapOptionZ(
3✔
969
                        inp.Params.StartingFeeRate,
3✔
970
                        func(feeRate chainfee.SatPerKWeight) uint64 {
5✔
971
                                return uint64(feeRate.FeePerVByte())
2✔
972
                        })
2✔
973

974
                ps := &PendingSweep{
3✔
975
                        Outpoint:             op,
3✔
976
                        WitnessType:          witnessType,
3✔
977
                        AmountSat:            amountSat,
3✔
978
                        SatPerVbyte:          satPerVbyte,
3✔
979
                        BroadcastAttempts:    broadcastAttempts,
3✔
980
                        Immediate:            inp.Params.Immediate,
3✔
981
                        Budget:               uint64(inp.Params.Budget),
3✔
982
                        DeadlineHeight:       inp.DeadlineHeight,
3✔
983
                        RequestedSatPerVbyte: startingFeeRate,
3✔
984
                }
3✔
985
                rpcPendingSweeps = append(rpcPendingSweeps, ps)
3✔
986
        }
987

988
        return &PendingSweepsResponse{
3✔
989
                PendingSweeps: rpcPendingSweeps,
3✔
990
        }, nil
3✔
991
}
992

993
// UnmarshallOutPoint converts an outpoint from its lnrpc type to its canonical
994
// type.
995
func UnmarshallOutPoint(op *lnrpc.OutPoint) (*wire.OutPoint, error) {
3✔
996
        if op == nil {
3✔
997
                return nil, fmt.Errorf("empty outpoint provided")
×
998
        }
×
999

1000
        var hash chainhash.Hash
3✔
1001
        switch {
3✔
1002
        // Return an error if both txid fields are unpopulated.
1003
        case len(op.TxidBytes) == 0 && len(op.TxidStr) == 0:
×
1004
                return nil, fmt.Errorf("TxidBytes and TxidStr are both " +
×
1005
                        "unspecified")
×
1006

1007
        // The hash was provided as raw bytes.
1008
        case len(op.TxidBytes) != 0:
3✔
1009
                copy(hash[:], op.TxidBytes)
3✔
1010

1011
        // The hash was provided as a hex-encoded string.
1012
        case len(op.TxidStr) != 0:
×
1013
                h, err := chainhash.NewHashFromStr(op.TxidStr)
×
1014
                if err != nil {
×
1015
                        return nil, err
×
1016
                }
×
1017
                hash = *h
×
1018
        }
1019

1020
        return &wire.OutPoint{
3✔
1021
                Hash:  hash,
3✔
1022
                Index: op.OutputIndex,
3✔
1023
        }, nil
3✔
1024
}
1025

1026
// validateBumpFeeRequest makes sure the deprecated fields are not used when
1027
// the new fields are set.
1028
func validateBumpFeeRequest(in *BumpFeeRequest) (
1029
        fn.Option[chainfee.SatPerKWeight], bool, error) {
3✔
1030

3✔
1031
        // Get the specified fee rate if set.
3✔
1032
        satPerKwOpt := fn.None[chainfee.SatPerKWeight]()
3✔
1033

3✔
1034
        // We only allow using either the deprecated field or the new field.
3✔
1035
        switch {
3✔
1036
        case in.SatPerByte != 0 && in.SatPerVbyte != 0:
×
1037
                return satPerKwOpt, false, fmt.Errorf("either SatPerByte or " +
×
1038
                        "SatPerVbyte should be set, but not both")
×
1039

1040
        case in.SatPerByte != 0:
×
1041
                satPerKw := chainfee.SatPerVByte(
×
1042
                        in.SatPerByte,
×
1043
                ).FeePerKWeight()
×
1044
                satPerKwOpt = fn.Some(satPerKw)
×
1045

1046
        case in.SatPerVbyte != 0:
2✔
1047
                satPerKw := chainfee.SatPerVByte(
2✔
1048
                        in.SatPerVbyte,
2✔
1049
                ).FeePerKWeight()
2✔
1050
                satPerKwOpt = fn.Some(satPerKw)
2✔
1051
        }
1052

1053
        var immediate bool
3✔
1054
        switch {
3✔
1055
        case in.Force && in.Immediate:
×
1056
                return satPerKwOpt, false, fmt.Errorf("either Force or " +
×
1057
                        "Immediate should be set, but not both")
×
1058

1059
        case in.Force:
×
1060
                immediate = in.Force
×
1061

1062
        case in.Immediate:
3✔
1063
                immediate = in.Immediate
3✔
1064
        }
1065

1066
        return satPerKwOpt, immediate, nil
3✔
1067
}
1068

1069
// prepareSweepParams creates the sweep params to be used for the sweeper. It
1070
// returns the new params and a bool indicating whether this is an existing
1071
// input.
1072
func (w *WalletKit) prepareSweepParams(in *BumpFeeRequest,
1073
        op wire.OutPoint, currentHeight int32) (sweep.Params, bool, error) {
3✔
1074

3✔
1075
        // Return an error if both deprecated and new fields are used.
3✔
1076
        feerate, immediate, err := validateBumpFeeRequest(in)
3✔
1077
        if err != nil {
3✔
1078
                return sweep.Params{}, false, err
×
1079
        }
×
1080

1081
        // Get the current pending inputs.
1082
        inputMap, err := w.cfg.Sweeper.PendingInputs()
3✔
1083
        if err != nil {
3✔
1084
                return sweep.Params{}, false, fmt.Errorf("unable to get "+
×
1085
                        "pending inputs: %w", err)
×
1086
        }
×
1087

1088
        // Find the pending input.
1089
        //
1090
        // TODO(yy): act differently based on the state of the input?
1091
        inp, ok := inputMap[op]
3✔
1092

3✔
1093
        if !ok {
5✔
1094
                // NOTE: if this input doesn't exist and the new budget is not
2✔
1095
                // specified, the params would have a zero budget.
2✔
1096
                params := sweep.Params{
2✔
1097
                        Immediate:       immediate,
2✔
1098
                        StartingFeeRate: feerate,
2✔
1099
                        Budget:          btcutil.Amount(in.Budget),
2✔
1100
                }
2✔
1101
                if in.TargetConf != 0 {
2✔
1102
                        params.DeadlineHeight = fn.Some(
×
1103
                                int32(in.TargetConf) + currentHeight,
×
1104
                        )
×
1105
                }
×
1106

1107
                return params, ok, nil
2✔
1108
        }
1109

1110
        // Find the existing budget used for this input. Note that this value
1111
        // must be greater than zero.
1112
        budget := inp.Params.Budget
3✔
1113

3✔
1114
        // Set the new budget if specified.
3✔
1115
        if in.Budget != 0 {
6✔
1116
                budget = btcutil.Amount(in.Budget)
3✔
1117
        }
3✔
1118

1119
        // For an existing input, we assign it first, then overwrite it if
1120
        // a deadline is requested.
1121
        deadline := inp.Params.DeadlineHeight
3✔
1122

3✔
1123
        // Set the deadline if target conf is specified.
3✔
1124
        //
3✔
1125
        // TODO(yy): upgrade `falafel` so we can make this field optional. Atm
3✔
1126
        // we cannot distinguish between user's not setting the field and
3✔
1127
        // setting it to 0.
3✔
1128
        if in.TargetConf != 0 {
6✔
1129
                deadline = fn.Some(int32(in.TargetConf) + currentHeight)
3✔
1130
        }
3✔
1131

1132
        // Prepare the new sweep params.
1133
        //
1134
        // NOTE: if this input doesn't exist and the new budget is not
1135
        // specified, the params would have a zero budget.
1136
        params := sweep.Params{
3✔
1137
                Immediate:       immediate,
3✔
1138
                StartingFeeRate: feerate,
3✔
1139
                DeadlineHeight:  deadline,
3✔
1140
                Budget:          budget,
3✔
1141
        }
3✔
1142

3✔
1143
        if ok {
6✔
1144
                log.Infof("[BumpFee]: bumping fee for existing input=%v, old "+
3✔
1145
                        "params=%v, new params=%v", op, inp.Params, params)
3✔
1146
        }
3✔
1147

1148
        return params, ok, nil
3✔
1149
}
1150

1151
// BumpFee allows bumping the fee rate of an arbitrary input. A fee preference
1152
// can be expressed either as a specific fee rate or a delta of blocks in which
1153
// the output should be swept on-chain within. If a fee preference is not
1154
// explicitly specified, then an error is returned. The status of the input
1155
// sweep can be checked through the PendingSweeps RPC.
1156
func (w *WalletKit) BumpFee(ctx context.Context,
1157
        in *BumpFeeRequest) (*BumpFeeResponse, error) {
3✔
1158

3✔
1159
        // Parse the outpoint from the request.
3✔
1160
        op, err := UnmarshallOutPoint(in.Outpoint)
3✔
1161
        if err != nil {
3✔
1162
                return nil, err
×
1163
        }
×
1164

1165
        // Get the current height so we can calculate the deadline height.
1166
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
3✔
1167
        if err != nil {
3✔
1168
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
1169
                        err)
×
1170
        }
×
1171

1172
        // We now create a new sweeping params and update it in the sweeper.
1173
        // This will complicate the RBF conditions if this input has already
1174
        // been offered to sweeper before and it has already been included in a
1175
        // tx with other inputs. If this is the case, two results are possible:
1176
        // - either this input successfully RBFed the existing tx, or,
1177
        // - the budget of this input was not enough to RBF the existing tx.
1178
        params, existing, err := w.prepareSweepParams(in, *op, currentHeight)
3✔
1179
        if err != nil {
3✔
1180
                return nil, err
×
1181
        }
×
1182

1183
        // If this input exists, we will update its params.
1184
        if existing {
6✔
1185
                _, err = w.cfg.Sweeper.UpdateParams(*op, params)
3✔
1186
                if err != nil {
3✔
1187
                        return nil, err
×
1188
                }
×
1189

1190
                return &BumpFeeResponse{
3✔
1191
                        Status: "Successfully registered rbf-tx with sweeper",
3✔
1192
                }, nil
3✔
1193
        }
1194

1195
        // Otherwise, create a new sweeping request for this input.
1196
        err = w.sweepNewInput(op, uint32(currentHeight), params)
2✔
1197
        if err != nil {
2✔
1198
                return nil, err
×
1199
        }
×
1200

1201
        return &BumpFeeResponse{
2✔
1202
                Status: "Successfully registered CPFP-tx with the sweeper",
2✔
1203
        }, nil
2✔
1204
}
1205

1206
// getWaitingCloseChannel returns the waiting close channel in case it does
1207
// exist in the underlying channel state database.
1208
func (w *WalletKit) getWaitingCloseChannel(
1209
        chanPoint wire.OutPoint) (*channeldb.OpenChannel, error) {
2✔
1210

2✔
1211
        // Fetch all channels, which still have their commitment transaction not
2✔
1212
        // confirmed (waiting close channels).
2✔
1213
        chans, err := w.cfg.ChanStateDB.FetchWaitingCloseChannels()
2✔
1214
        if err != nil {
2✔
1215
                return nil, err
×
1216
        }
×
1217

1218
        channel := fn.Find(chans, func(c *channeldb.OpenChannel) bool {
4✔
1219
                return c.FundingOutpoint == chanPoint
2✔
1220
        })
2✔
1221

1222
        return channel.UnwrapOrErr(errors.New("channel not found"))
2✔
1223
}
1224

1225
// BumpForceCloseFee bumps the fee rate of an unconfirmed anchor channel. It
1226
// updates the new fee rate parameters with the sweeper subsystem. Additionally
1227
// it will try to create anchor cpfp transactions for all possible commitment
1228
// transactions (local, remote, remote-dangling) so depending on which
1229
// commitment is in the local mempool only one of them will succeed in being
1230
// broadcasted.
1231
func (w *WalletKit) BumpForceCloseFee(_ context.Context,
1232
        in *BumpForceCloseFeeRequest) (*BumpForceCloseFeeResponse, error) {
2✔
1233

2✔
1234
        if in.ChanPoint == nil {
2✔
1235
                return nil, fmt.Errorf("no chan_point provided")
×
1236
        }
×
1237

1238
        lnrpcOutpoint, err := lnrpc.GetChannelOutPoint(in.ChanPoint)
2✔
1239
        if err != nil {
2✔
1240
                return nil, err
×
1241
        }
×
1242

1243
        outPoint, err := UnmarshallOutPoint(lnrpcOutpoint)
2✔
1244
        if err != nil {
2✔
1245
                return nil, err
×
1246
        }
×
1247

1248
        // Get the relevant channel if it is in the waiting close state.
1249
        channel, err := w.getWaitingCloseChannel(*outPoint)
2✔
1250
        if err != nil {
2✔
1251
                return nil, err
×
1252
        }
×
1253

1254
        if !channel.ChanType.HasAnchors() {
2✔
1255
                return nil, fmt.Errorf("not able to bump the fee of a " +
×
1256
                        "non-anchor channel")
×
1257
        }
×
1258

1259
        // Match pending sweeps with commitments of the channel for which a bump
1260
        // is requested. Depending on the commitment state when force closing
1261
        // the channel we might have up to 3 commitments to consider when
1262
        // bumping the fee.
1263
        commitSet := fn.NewSet[chainhash.Hash]()
2✔
1264

2✔
1265
        if channel.LocalCommitment.CommitTx != nil {
4✔
1266
                localTxID := channel.LocalCommitment.CommitTx.TxHash()
2✔
1267
                commitSet.Add(localTxID)
2✔
1268
        }
2✔
1269

1270
        if channel.RemoteCommitment.CommitTx != nil {
4✔
1271
                remoteTxID := channel.RemoteCommitment.CommitTx.TxHash()
2✔
1272
                commitSet.Add(remoteTxID)
2✔
1273
        }
2✔
1274

1275
        // Check whether there was a dangling commitment at the time the channel
1276
        // was force closed.
1277
        remoteCommitDiff, err := channel.RemoteCommitChainTip()
2✔
1278
        if err != nil && !errors.Is(err, channeldb.ErrNoPendingCommit) {
2✔
1279
                return nil, err
×
1280
        }
×
1281

1282
        if remoteCommitDiff != nil {
2✔
1283
                hash := remoteCommitDiff.Commitment.CommitTx.TxHash()
×
1284
                commitSet.Add(hash)
×
1285
        }
×
1286

1287
        // Retrieve all of the outputs the UtxoSweeper is currently trying to
1288
        // sweep.
1289
        inputsMap, err := w.cfg.Sweeper.PendingInputs()
2✔
1290
        if err != nil {
2✔
1291
                return nil, err
×
1292
        }
×
1293

1294
        // Get the current height so we can calculate the deadline height.
1295
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
2✔
1296
        if err != nil {
2✔
1297
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
1298
                        err)
×
1299
        }
×
1300

1301
        pendingSweeps := maps.Values(inputsMap)
2✔
1302

2✔
1303
        // Discard everything except for the anchor sweeps.
2✔
1304
        anchors := fn.Filter(
2✔
1305
                pendingSweeps,
2✔
1306
                func(sweep *sweep.PendingInputResponse) bool {
4✔
1307
                        // Only filter for anchor inputs because these are the
2✔
1308
                        // only inputs which can be used to bump a closed
2✔
1309
                        // unconfirmed commitment transaction.
2✔
1310
                        isCommitAnchor := sweep.WitnessType ==
2✔
1311
                                input.CommitmentAnchor
2✔
1312
                        isTaprootSweepSpend := sweep.WitnessType ==
2✔
1313
                                input.TaprootAnchorSweepSpend
2✔
1314
                        if !isCommitAnchor && !isTaprootSweepSpend {
2✔
1315
                                return false
×
1316
                        }
×
1317

1318
                        return commitSet.Contains(sweep.OutPoint.Hash)
2✔
1319
                },
1320
        )
1321

1322
        if len(anchors) == 0 {
2✔
1323
                return nil, fmt.Errorf("unable to find pending anchor outputs")
×
1324
        }
×
1325

1326
        // Filter all relevant anchor sweeps and update the sweep request.
1327
        for _, anchor := range anchors {
4✔
1328
                // Anchor cpfp bump request are predictable because they are
2✔
1329
                // swept separately hence not batched with other sweeps (they
2✔
1330
                // are marked with the exclusive group flag). Bumping the fee
2✔
1331
                // rate does not create any conflicting fee bump conditions.
2✔
1332
                // Either the rbf requirements are met or the bump is rejected
2✔
1333
                // by the mempool rules.
2✔
1334
                params, existing, err := w.prepareSweepParams(
2✔
1335
                        &BumpFeeRequest{
2✔
1336
                                Outpoint:    lnrpcOutpoint,
2✔
1337
                                TargetConf:  in.DeadlineDelta,
2✔
1338
                                SatPerVbyte: in.StartingFeerate,
2✔
1339
                                Immediate:   in.Immediate,
2✔
1340
                                Budget:      in.Budget,
2✔
1341
                        }, anchor.OutPoint, currentHeight,
2✔
1342
                )
2✔
1343
                if err != nil {
2✔
1344
                        return nil, err
×
1345
                }
×
1346

1347
                // There might be the case when an anchor sweep is confirmed
1348
                // between fetching the pending sweeps and preparing the sweep
1349
                // params. We log this case and proceed.
1350
                if !existing {
2✔
1351
                        log.Errorf("Sweep anchor input(%v) not known to the " +
×
1352
                                "sweeper subsystem")
×
1353
                        continue
×
1354
                }
1355

1356
                _, err = w.cfg.Sweeper.UpdateParams(anchor.OutPoint, params)
2✔
1357
                if err != nil {
2✔
1358
                        return nil, err
×
1359
                }
×
1360
        }
1361

1362
        return &BumpForceCloseFeeResponse{
2✔
1363
                Status: "Successfully registered anchor-cpfp transaction to" +
2✔
1364
                        "bump channel force close transaction",
2✔
1365
        }, nil
2✔
1366
}
1367

1368
// sweepNewInput handles the case where an input is seen the first time by the
1369
// sweeper. It will fetch the output from the wallet and construct an input and
1370
// offer it to the sweeper.
1371
//
1372
// NOTE: if the budget is not set, the default budget ratio is used.
1373
func (w *WalletKit) sweepNewInput(op *wire.OutPoint, currentHeight uint32,
1374
        params sweep.Params) error {
2✔
1375

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

2✔
1378
        // Since the sweeper is not aware of the input, we'll assume the user
2✔
1379
        // is attempting to bump an unconfirmed transaction's fee rate by
2✔
1380
        // sweeping an output within it under control of the wallet with a
2✔
1381
        // higher fee rate. In this case, this will be a CPFP.
2✔
1382
        //
2✔
1383
        // We'll gather all of the information required by the UtxoSweeper in
2✔
1384
        // order to sweep the output.
2✔
1385
        utxo, err := w.cfg.Wallet.FetchOutpointInfo(op)
2✔
1386
        if err != nil {
2✔
1387
                return err
×
1388
        }
×
1389

1390
        // We're only able to bump the fee of unconfirmed transactions.
1391
        if utxo.Confirmations > 0 {
2✔
1392
                return errors.New("unable to bump fee of a confirmed " +
×
1393
                        "transaction")
×
1394
        }
×
1395

1396
        // If there's no budget set, use the default value.
1397
        if params.Budget == 0 {
4✔
1398
                params.Budget = utxo.Value.MulF64(
2✔
1399
                        contractcourt.DefaultBudgetRatio,
2✔
1400
                )
2✔
1401
        }
2✔
1402

1403
        signDesc := &input.SignDescriptor{
2✔
1404
                Output: &wire.TxOut{
2✔
1405
                        PkScript: utxo.PkScript,
2✔
1406
                        Value:    int64(utxo.Value),
2✔
1407
                },
2✔
1408
                HashType: txscript.SigHashAll,
2✔
1409
        }
2✔
1410

2✔
1411
        var witnessType input.WitnessType
2✔
1412
        switch utxo.AddressType {
2✔
1413
        case lnwallet.WitnessPubKey:
×
1414
                witnessType = input.WitnessKeyHash
×
1415
        case lnwallet.NestedWitnessPubKey:
×
1416
                witnessType = input.NestedWitnessKeyHash
×
1417
        case lnwallet.TaprootPubkey:
2✔
1418
                witnessType = input.TaprootPubKeySpend
2✔
1419
                signDesc.HashType = txscript.SigHashDefault
2✔
1420
        default:
×
1421
                return fmt.Errorf("unknown input witness %v", op)
×
1422
        }
1423

1424
        log.Infof("[BumpFee]: bumping fee for new input=%v, params=%v", op,
2✔
1425
                params)
2✔
1426

2✔
1427
        inp := input.NewBaseInput(op, witnessType, signDesc, currentHeight)
2✔
1428
        if _, err = w.cfg.Sweeper.SweepInput(inp, params); err != nil {
2✔
1429
                return err
×
1430
        }
×
1431

1432
        return nil
2✔
1433
}
1434

1435
// ListSweeps returns a list of the sweeps that our node has published.
1436
func (w *WalletKit) ListSweeps(ctx context.Context,
1437
        in *ListSweepsRequest) (*ListSweepsResponse, error) {
3✔
1438

3✔
1439
        sweeps, err := w.cfg.Sweeper.ListSweeps()
3✔
1440
        if err != nil {
3✔
1441
                return nil, err
×
1442
        }
×
1443

1444
        sweepTxns := make(map[string]bool)
3✔
1445
        for _, sweep := range sweeps {
6✔
1446
                sweepTxns[sweep.String()] = true
3✔
1447
        }
3✔
1448

1449
        // Some of our sweeps could have been replaced by fee, or dropped out
1450
        // of the mempool. Here, we lookup our wallet transactions so that we
1451
        // can match our list of sweeps against the list of transactions that
1452
        // the wallet is still tracking. Sweeps are currently always swept to
1453
        // the default wallet account.
1454
        txns, firstIdx, lastIdx, err := w.cfg.Wallet.ListTransactionDetails(
3✔
1455
                in.StartHeight, btcwallet.UnconfirmedHeight,
3✔
1456
                lnwallet.DefaultAccountName, 0, 0,
3✔
1457
        )
3✔
1458
        if err != nil {
3✔
1459
                return nil, err
×
1460
        }
×
1461

1462
        var (
3✔
1463
                txids     []string
3✔
1464
                txDetails []*lnwallet.TransactionDetail
3✔
1465
        )
3✔
1466

3✔
1467
        for _, tx := range txns {
6✔
1468
                _, ok := sweepTxns[tx.Hash.String()]
3✔
1469
                if !ok {
6✔
1470
                        continue
3✔
1471
                }
1472

1473
                // Add the txid or full tx details depending on whether we want
1474
                // verbose output or not.
1475
                if in.Verbose {
6✔
1476
                        txDetails = append(txDetails, tx)
3✔
1477
                } else {
6✔
1478
                        txids = append(txids, tx.Hash.String())
3✔
1479
                }
3✔
1480
        }
1481

1482
        if in.Verbose {
6✔
1483
                return &ListSweepsResponse{
3✔
1484
                        Sweeps: &ListSweepsResponse_TransactionDetails{
3✔
1485
                                TransactionDetails: lnrpc.RPCTransactionDetails(
3✔
1486
                                        txDetails, firstIdx, lastIdx,
3✔
1487
                                ),
3✔
1488
                        },
3✔
1489
                }, nil
3✔
1490
        }
3✔
1491

1492
        return &ListSweepsResponse{
3✔
1493
                Sweeps: &ListSweepsResponse_TransactionIds{
3✔
1494
                        TransactionIds: &ListSweepsResponse_TransactionIDs{
3✔
1495
                                TransactionIds: txids,
3✔
1496
                        },
3✔
1497
                },
3✔
1498
        }, nil
3✔
1499
}
1500

1501
// LabelTransaction adds a label to a transaction.
1502
func (w *WalletKit) LabelTransaction(ctx context.Context,
1503
        req *LabelTransactionRequest) (*LabelTransactionResponse, error) {
3✔
1504

3✔
1505
        // Check that the label provided in non-zero.
3✔
1506
        if len(req.Label) == 0 {
6✔
1507
                return nil, ErrZeroLabel
3✔
1508
        }
3✔
1509

1510
        // Validate the length of the non-zero label. We do not need to use the
1511
        // label returned here, because the original is non-zero so will not
1512
        // be replaced.
1513
        if _, err := labels.ValidateAPI(req.Label); err != nil {
3✔
1514
                return nil, err
×
1515
        }
×
1516

1517
        hash, err := chainhash.NewHash(req.Txid)
3✔
1518
        if err != nil {
3✔
1519
                return nil, err
×
1520
        }
×
1521

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

3✔
1524
        return &LabelTransactionResponse{
3✔
1525
                Status: fmt.Sprintf("transaction label '%s' added", req.Label),
3✔
1526
        }, err
3✔
1527
}
1528

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

3✔
1562
        coinSelectionStrategy, err := lnrpc.UnmarshallCoinSelectionStrategy(
3✔
1563
                req.CoinSelectionStrategy, w.cfg.CoinSelectionStrategy,
3✔
1564
        )
3✔
1565
        if err != nil {
3✔
1566
                return nil, err
×
1567
        }
×
1568

1569
        // Determine the desired transaction fee.
1570
        var feeSatPerKW chainfee.SatPerKWeight
3✔
1571
        switch {
3✔
1572
        // Estimate the fee by the target number of blocks to confirmation.
1573
        case req.GetTargetConf() != 0:
×
1574
                targetConf := req.GetTargetConf()
×
1575
                if targetConf < 2 {
×
1576
                        return nil, fmt.Errorf("confirmation target must be " +
×
1577
                                "greater than 1")
×
1578
                }
×
1579

1580
                feeSatPerKW, err = w.cfg.FeeEstimator.EstimateFeePerKW(
×
1581
                        targetConf,
×
1582
                )
×
1583
                if err != nil {
×
1584
                        return nil, fmt.Errorf("could not estimate fee: %w",
×
1585
                                err)
×
1586
                }
×
1587

1588
        // Convert the fee to sat/kW from the specified sat/vByte.
1589
        case req.GetSatPerVbyte() != 0:
3✔
1590
                feeSatPerKW = chainfee.SatPerKVByte(
3✔
1591
                        req.GetSatPerVbyte() * 1000,
3✔
1592
                ).FeePerKWeight()
3✔
1593

1594
        case req.GetSatPerKw() != 0:
×
1595
                feeSatPerKW = chainfee.SatPerKWeight(req.GetSatPerKw())
×
1596

1597
        default:
×
1598
                return nil, fmt.Errorf("fee definition missing, need to " +
×
1599
                        "specify either target_conf, sat_per_vbyte or " +
×
1600
                        "sat_per_kw")
×
1601
        }
1602

1603
        // Then, we'll extract the minimum number of confirmations that each
1604
        // output we use to fund the transaction should satisfy.
1605
        minConfs, err := lnrpc.ExtractMinConfs(
3✔
1606
                req.GetMinConfs(), req.GetSpendUnconfirmed(),
3✔
1607
        )
3✔
1608
        if err != nil {
3✔
1609
                return nil, err
×
1610
        }
×
1611

1612
        // We'll assume the PSBT will be funded by the default account unless
1613
        // otherwise specified.
1614
        account := lnwallet.DefaultAccountName
3✔
1615
        if req.Account != "" {
6✔
1616
                account = req.Account
3✔
1617
        }
3✔
1618

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

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

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

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

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

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

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

1679
                        changeIndex = t.ExistingOutputIndex
3✔
1680

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

1688
                        changeType = chanfunding.ExistingChangeAddress
3✔
1689

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

1701
                        default:
×
1702
                                changeType = chanfunding.P2WKHChangeAddress
×
1703
                        }
1704

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

1709
                maxFeeRatio := chanfunding.DefaultMaxFeeRatio
3✔
1710

3✔
1711
                if req.MaxFeeRatio != 0 {
3✔
1712
                        maxFeeRatio = req.MaxFeeRatio
×
1713
                }
×
1714

1715
                // Run the actual funding process now, using the channel funding
1716
                // coin selection algorithm.
1717
                return w.fundPsbtCoinSelect(
3✔
1718
                        account, changeIndex, packet, minConfs, changeType,
3✔
1719
                        feeSatPerKW, coinSelectionStrategy, maxFeeRatio,
3✔
1720
                )
3✔
1721

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

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

1738
                        if !addr.IsForNet(w.cfg.ChainParams) {
3✔
1739
                                return nil, fmt.Errorf("address is not for %s",
×
1740
                                        w.cfg.ChainParams.Name)
×
1741
                        }
×
1742

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

1750
                        txOut = append(txOut, &wire.TxOut{
3✔
1751
                                Value:    int64(amt),
3✔
1752
                                PkScript: pkScript,
3✔
1753
                        })
3✔
1754
                }
1755

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

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

1772
                // Run the actual funding process now, using the internal
1773
                // wallet.
1774
                return w.fundPsbtInternalWallet(
3✔
1775
                        account, keyScopeFromChangeAddressType(req.ChangeType),
3✔
1776
                        packet, minConfs, feeSatPerKW, coinSelectionStrategy,
3✔
1777
                )
3✔
1778

1779
        default:
×
1780
                return nil, fmt.Errorf("transaction template missing, need " +
×
1781
                        "to specify either PSBT or raw TX template")
×
1782
        }
1783
}
1784

1785
// fundPsbtInternalWallet uses the "old" PSBT funding method of the internal
1786
// wallet that does not allow specifying custom inputs while selecting coins.
1787
func (w *WalletKit) fundPsbtInternalWallet(account string,
1788
        keyScope *waddrmgr.KeyScope, packet *psbt.Packet, minConfs int32,
1789
        feeSatPerKW chainfee.SatPerKWeight,
1790
        strategy base.CoinSelectionStrategy) (*FundPsbtResponse, error) {
3✔
1791

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

1809
                        // filterFn makes sure utxos which are unconfirmed and
1810
                        // still used by the sweeper are not used.
1811
                        filterFn := func(u *lnwallet.Utxo) bool {
6✔
1812
                                // Confirmed utxos are always allowed.
3✔
1813
                                if u.Confirmations > 0 {
6✔
1814
                                        return true
3✔
1815
                                }
3✔
1816

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

3✔
1826
                                        return false
3✔
1827
                                }
3✔
1828

1829
                                return true
×
1830
                        }
1831

1832
                        eligibleUtxos := fn.Filter(utxos, filterFn)
3✔
1833

3✔
1834
                        // Validate all inputs against our known list of UTXOs
3✔
1835
                        // now.
3✔
1836
                        err = verifyInputsUnspent(
3✔
1837
                                packet.UnsignedTx.TxIn, eligibleUtxos,
3✔
1838
                        )
3✔
1839
                        if err != nil {
6✔
1840
                                return err
3✔
1841
                        }
3✔
1842
                }
1843

1844
                // currentHeight is needed to determine whether the internal
1845
                // wallet utxo is still unconfirmed.
1846
                _, currentHeight, err := w.cfg.Chain.GetBestBlock()
3✔
1847
                if err != nil {
3✔
1848
                        return fmt.Errorf("unable to retrieve current "+
×
1849
                                "height: %v", err)
×
1850
                }
×
1851

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

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

1875
                        return allowed
3✔
1876
                }
1877

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

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

1903
                response, err = w.lockAndCreateFundingResponse(
3✔
1904
                        packet, outpoints, changeIndex,
3✔
1905
                )
3✔
1906

3✔
1907
                return err
3✔
1908
        })
1909
        if err != nil {
6✔
1910
                return nil, err
3✔
1911
        }
3✔
1912

1913
        return response, nil
3✔
1914
}
1915

1916
// fundPsbtCoinSelect uses the "new" PSBT funding method using the channel
1917
// funding coin selection algorithm that allows specifying custom inputs while
1918
// selecting coins.
1919
func (w *WalletKit) fundPsbtCoinSelect(account string, changeIndex int32,
1920
        packet *psbt.Packet, minConfs int32,
1921
        changeType chanfunding.ChangeAddressType,
1922
        feeRate chainfee.SatPerKWeight, strategy base.CoinSelectionStrategy,
1923
        maxFeeRatio float64) (*FundPsbtResponse, error) {
3✔
1924

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

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

1945
        // Before we select anything, we need to calculate the input, output and
1946
        // current weight amounts. While doing that we also ensure the PSBT has
1947
        // all the required information we require at this step.
1948
        var (
3✔
1949
                inputSum, outputSum btcutil.Amount
3✔
1950
                estimator           input.TxWeightEstimator
3✔
1951
        )
3✔
1952
        for i := range packet.Inputs {
6✔
1953
                in := packet.Inputs[i]
3✔
1954

3✔
1955
                err := btcwallet.EstimateInputWeight(&in, &estimator)
3✔
1956
                if err != nil {
3✔
1957
                        return nil, fmt.Errorf("error estimating input "+
×
1958
                                "weight: %w", err)
×
1959
                }
×
1960

1961
                inputSum += btcutil.Amount(in.WitnessUtxo.Value)
3✔
1962
        }
1963
        for i := range packet.UnsignedTx.TxOut {
6✔
1964
                out := packet.UnsignedTx.TxOut[i]
3✔
1965

3✔
1966
                estimator.AddOutput(out.PkScript)
3✔
1967
                outputSum += btcutil.Amount(out.Value)
3✔
1968
        }
3✔
1969

1970
        // The amount we want to fund is the total output sum plus the current
1971
        // fee estimate, minus the sum of any already specified inputs. Since we
1972
        // pass the estimator of the current transaction into the coin selection
1973
        // algorithm, we don't need to subtract the fees here.
1974
        fundingAmount := outputSum - inputSum
3✔
1975

3✔
1976
        var changeDustLimit btcutil.Amount
3✔
1977
        switch changeType {
3✔
1978
        case chanfunding.P2TRChangeAddress:
×
1979
                changeDustLimit = lnwallet.DustLimitForSize(input.P2TRSize)
×
1980

1981
        case chanfunding.P2WKHChangeAddress:
×
1982
                changeDustLimit = lnwallet.DustLimitForSize(input.P2WPKHSize)
×
1983

1984
        case chanfunding.ExistingChangeAddress:
3✔
1985
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
3✔
1986
                changeDustLimit = lnwallet.DustLimitForSize(
3✔
1987
                        len(changeOut.PkScript),
3✔
1988
                )
3✔
1989
        }
1990

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

2003
                case chanfunding.P2WKHChangeAddress:
×
2004
                        estimator.AddP2WKHOutput()
×
2005
                }
2006
                packetFeeWithChange := feeRate.FeeForWeight(estimator.Weight())
×
2007

×
2008
                changeAmt, needMore, err := chanfunding.CalculateChangeAmount(
×
2009
                        inputSum, outputSum, packetFeeNoChange,
×
2010
                        packetFeeWithChange, changeDustLimit, changeType,
×
2011
                        maxFeeRatio,
×
2012
                )
×
2013
                if err != nil {
×
2014
                        return nil, fmt.Errorf("error calculating change "+
×
2015
                                "amount: %w", err)
×
2016
                }
×
2017

2018
                // We shouldn't get into this branch if the input sum isn't
2019
                // enough to pay for the current package without a change
2020
                // output. So this should never be non-zero.
2021
                if needMore != 0 {
×
2022
                        return nil, fmt.Errorf("internal error with change " +
×
2023
                                "amount calculation")
×
2024
                }
×
2025

2026
                if changeAmt > 0 {
×
2027
                        changeIndex, err = w.handleChange(
×
2028
                                packet, changeIndex, int64(changeAmt),
×
2029
                                changeType, account,
×
2030
                        )
×
2031
                        if err != nil {
×
2032
                                return nil, fmt.Errorf("error handling change "+
×
2033
                                        "amount: %w", err)
×
2034
                        }
×
2035
                }
2036

2037
                // We're done. Let's serialize and return the updated package.
2038
                return w.lockAndCreateFundingResponse(packet, nil, changeIndex)
×
2039
        }
2040

2041
        // The RPC parsing part is now over. Several of the following operations
2042
        // require us to hold the global coin selection lock, so we do the rest
2043
        // of the tasks while holding the lock. The result is a list of locked
2044
        // UTXOs.
2045
        var response *FundPsbtResponse
3✔
2046
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
6✔
2047
                // Get a list of all unspent witness outputs.
3✔
2048
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
3✔
2049
                        minConfs, defaultMaxConf, account,
3✔
2050
                )
3✔
2051
                if err != nil {
3✔
2052
                        return err
×
2053
                }
×
2054

2055
                coins := make([]base.Coin, len(utxos))
3✔
2056
                for i, utxo := range utxos {
6✔
2057
                        coins[i] = base.Coin{
3✔
2058
                                TxOut: wire.TxOut{
3✔
2059
                                        Value:    int64(utxo.Value),
3✔
2060
                                        PkScript: utxo.PkScript,
3✔
2061
                                },
3✔
2062
                                OutPoint: utxo.OutPoint,
3✔
2063
                        }
3✔
2064
                }
3✔
2065

2066
                selectedCoins, changeAmount, err := chanfunding.CoinSelect(
3✔
2067
                        feeRate, fundingAmount, changeDustLimit, coins,
3✔
2068
                        strategy, estimator, changeType, maxFeeRatio,
3✔
2069
                )
3✔
2070
                if err != nil {
3✔
2071
                        return fmt.Errorf("error selecting coins: %w", err)
×
2072
                }
×
2073

2074
                if changeAmount > 0 {
6✔
2075
                        changeIndex, err = w.handleChange(
3✔
2076
                                packet, changeIndex, int64(changeAmount),
3✔
2077
                                changeType, account,
3✔
2078
                        )
3✔
2079
                        if err != nil {
3✔
2080
                                return fmt.Errorf("error handling change "+
×
2081
                                        "amount: %w", err)
×
2082
                        }
×
2083
                }
2084

2085
                addedOutpoints := make([]wire.OutPoint, len(selectedCoins))
3✔
2086
                for i := range selectedCoins {
6✔
2087
                        coin := selectedCoins[i]
3✔
2088
                        addedOutpoints[i] = coin.OutPoint
3✔
2089

3✔
2090
                        packet.UnsignedTx.TxIn = append(
3✔
2091
                                packet.UnsignedTx.TxIn, &wire.TxIn{
3✔
2092
                                        PreviousOutPoint: coin.OutPoint,
3✔
2093
                                },
3✔
2094
                        )
3✔
2095
                        packet.Inputs = append(packet.Inputs, psbt.PInput{
3✔
2096
                                WitnessUtxo: &coin.TxOut,
3✔
2097
                        })
3✔
2098
                }
3✔
2099

2100
                // Now that we've added the bare TX inputs, we also need to add
2101
                // the more verbose input information to the packet, so a future
2102
                // signer doesn't need to do any lookups. We skip any inputs
2103
                // that our wallet doesn't own.
2104
                err = w.cfg.Wallet.DecorateInputs(packet, false)
3✔
2105
                if err != nil {
3✔
2106
                        return fmt.Errorf("error decorating inputs: %w", err)
×
2107
                }
×
2108

2109
                response, err = w.lockAndCreateFundingResponse(
3✔
2110
                        packet, addedOutpoints, changeIndex,
3✔
2111
                )
3✔
2112

3✔
2113
                return err
3✔
2114
        })
2115
        if err != nil {
3✔
2116
                return nil, err
×
2117
        }
×
2118

2119
        return response, nil
3✔
2120
}
2121

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

3✔
2127
        return w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
6✔
2128
                // Get a list of all unspent witness outputs.
3✔
2129
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
3✔
2130
                        minConfs, defaultMaxConf, account,
3✔
2131
                )
3✔
2132
                if err != nil {
3✔
2133
                        return fmt.Errorf("error fetching UTXOs: %w", err)
×
2134
                }
×
2135

2136
                // We'll now check that none of the inputs specified in the
2137
                // template are available to us. That means they either don't
2138
                // belong to us or are already locked by the user.
2139
                for _, txIn := range inputs {
6✔
2140
                        for _, utxo := range utxos {
6✔
2141
                                if txIn.PreviousOutPoint == utxo.OutPoint {
3✔
2142
                                        return fmt.Errorf("input %v is not "+
×
2143
                                                "locked", txIn.PreviousOutPoint)
×
2144
                                }
×
2145
                        }
2146
                }
2147

2148
                return nil
3✔
2149
        })
2150
}
2151

2152
// lockAndCreateFundingResponse locks the given outpoints and creates a funding
2153
// response with the serialized PSBT, the change index and the locked UTXOs.
2154
func (w *WalletKit) lockAndCreateFundingResponse(packet *psbt.Packet,
2155
        newOutpoints []wire.OutPoint, changeIndex int32) (*FundPsbtResponse,
2156
        error) {
3✔
2157

3✔
2158
        // Make sure we can properly serialize the packet. If this goes wrong
3✔
2159
        // then something isn't right with the inputs, and we probably shouldn't
3✔
2160
        // try to lock any of them.
3✔
2161
        var buf bytes.Buffer
3✔
2162
        err := packet.Serialize(&buf)
3✔
2163
        if err != nil {
3✔
2164
                return nil, fmt.Errorf("error serializing funded PSBT: %w", err)
×
2165
        }
×
2166

2167
        locks, err := lockInputs(w.cfg.Wallet, newOutpoints)
3✔
2168
        if err != nil {
3✔
2169
                return nil, fmt.Errorf("could not lock inputs: %w", err)
×
2170
        }
×
2171

2172
        // Convert the lock leases to the RPC format.
2173
        rpcLocks := marshallLeases(locks)
3✔
2174

3✔
2175
        return &FundPsbtResponse{
3✔
2176
                FundedPsbt:        buf.Bytes(),
3✔
2177
                ChangeOutputIndex: changeIndex,
3✔
2178
                LockedUtxos:       rpcLocks,
3✔
2179
        }, nil
3✔
2180
}
2181

2182
// handleChange is a closure that either adds the non-zero change amount to an
2183
// existing output or creates a change output. The function returns the new
2184
// change output index if a new change output was added.
2185
func (w *WalletKit) handleChange(packet *psbt.Packet, changeIndex int32,
2186
        changeAmount int64, changeType chanfunding.ChangeAddressType,
2187
        changeAccount string) (int32, error) {
3✔
2188

3✔
2189
        // Does an existing output get the change?
3✔
2190
        if changeIndex >= 0 {
6✔
2191
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
3✔
2192
                changeOut.Value += changeAmount
3✔
2193

3✔
2194
                return changeIndex, nil
3✔
2195
        }
3✔
2196

2197
        // The user requested a new change output.
2198
        addrType := addrTypeFromChangeAddressType(changeType)
×
2199
        changeAddr, err := w.cfg.Wallet.NewAddress(
×
2200
                addrType, true, changeAccount,
×
2201
        )
×
2202
        if err != nil {
×
2203
                return 0, fmt.Errorf("could not derive change address: %w", err)
×
2204
        }
×
2205

2206
        changeScript, err := txscript.PayToAddrScript(changeAddr)
×
2207
        if err != nil {
×
2208
                return 0, fmt.Errorf("could not derive change script: %w", err)
×
2209
        }
×
2210

2211
        // We need to add the derivation info for the change address in case it
2212
        // is a P2TR address. This is mostly to prove it's a bare BIP-0086
2213
        // address, which is required for some protocols (such as Taproot
2214
        // Assets).
2215
        pOut := psbt.POutput{}
×
2216
        _, isTaprootChangeAddr := changeAddr.(*btcutil.AddressTaproot)
×
2217
        if isTaprootChangeAddr {
×
2218
                changeAddrInfo, err := w.cfg.Wallet.AddressInfo(changeAddr)
×
2219
                if err != nil {
×
2220
                        return 0, fmt.Errorf("could not get address info: %w",
×
2221
                                err)
×
2222
                }
×
2223

2224
                deriv, trDeriv, _, err := btcwallet.Bip32DerivationFromAddress(
×
2225
                        changeAddrInfo,
×
2226
                )
×
2227
                if err != nil {
×
2228
                        return 0, fmt.Errorf("could not get derivation info: "+
×
2229
                                "%w", err)
×
2230
                }
×
2231

2232
                pOut.TaprootInternalKey = trDeriv.XOnlyPubKey
×
2233
                pOut.Bip32Derivation = []*psbt.Bip32Derivation{deriv}
×
2234
                pOut.TaprootBip32Derivation = []*psbt.TaprootBip32Derivation{
×
2235
                        trDeriv,
×
2236
                }
×
2237
        }
2238

2239
        newChangeIndex := int32(len(packet.Outputs))
×
2240
        packet.UnsignedTx.TxOut = append(
×
2241
                packet.UnsignedTx.TxOut, &wire.TxOut{
×
2242
                        Value:    changeAmount,
×
2243
                        PkScript: changeScript,
×
2244
                },
×
2245
        )
×
2246
        packet.Outputs = append(packet.Outputs, pOut)
×
2247

×
2248
        return newChangeIndex, nil
×
2249
}
2250

2251
// marshallLeases converts the lock leases to the RPC format.
2252
func marshallLeases(locks []*base.ListLeasedOutputResult) []*UtxoLease {
3✔
2253
        rpcLocks := make([]*UtxoLease, len(locks))
3✔
2254
        for idx, lock := range locks {
6✔
2255
                lock := lock
3✔
2256

3✔
2257
                rpcLocks[idx] = &UtxoLease{
3✔
2258
                        Id:         lock.LockID[:],
3✔
2259
                        Outpoint:   lnrpc.MarshalOutPoint(&lock.Outpoint),
3✔
2260
                        Expiration: uint64(lock.Expiration.Unix()),
3✔
2261
                        PkScript:   lock.PkScript,
3✔
2262
                        Value:      uint64(lock.Value),
3✔
2263
                }
3✔
2264
        }
3✔
2265

2266
        return rpcLocks
3✔
2267
}
2268

2269
// keyScopeFromChangeAddressType maps a ChangeAddressType from protobuf to a
2270
// KeyScope. If the type is ChangeAddressType_CHANGE_ADDRESS_TYPE_UNSPECIFIED,
2271
// it returns nil.
2272
func keyScopeFromChangeAddressType(
2273
        changeAddressType ChangeAddressType) *waddrmgr.KeyScope {
3✔
2274

3✔
2275
        switch changeAddressType {
3✔
2276
        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
3✔
2277
                return &waddrmgr.KeyScopeBIP0086
3✔
2278

2279
        default:
3✔
2280
                return nil
3✔
2281
        }
2282
}
2283

2284
// addrTypeFromChangeAddressType maps a chanfunding.ChangeAddressType to the
2285
// lnwallet.AddressType.
2286
func addrTypeFromChangeAddressType(
2287
        changeAddressType chanfunding.ChangeAddressType) lnwallet.AddressType {
×
2288

×
2289
        switch changeAddressType {
×
2290
        case chanfunding.P2TRChangeAddress:
×
2291
                return lnwallet.TaprootPubkey
×
2292

2293
        default:
×
2294
                return lnwallet.WitnessPubKey
×
2295
        }
2296
}
2297

2298
// SignPsbt expects a partial transaction with all inputs and outputs fully
2299
// declared and tries to sign all unsigned inputs that have all required fields
2300
// (UTXO information, BIP32 derivation information, witness or sig scripts)
2301
// set.
2302
// If no error is returned, the PSBT is ready to be given to the next signer or
2303
// to be finalized if lnd was the last signer.
2304
//
2305
// NOTE: This RPC only signs inputs (and only those it can sign), it does not
2306
// perform any other tasks (such as coin selection, UTXO locking or
2307
// input/output/fee value validation, PSBT finalization). Any input that is
2308
// incomplete will be skipped.
2309
func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) (
2310
        *SignPsbtResponse, error) {
3✔
2311

3✔
2312
        packet, err := psbt.NewFromRawBytes(
3✔
2313
                bytes.NewReader(req.FundedPsbt), false,
3✔
2314
        )
3✔
2315
        if err != nil {
3✔
2316
                log.Debugf("Error parsing PSBT: %v, raw input: %x", err,
×
2317
                        req.FundedPsbt)
×
2318
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
2319
        }
×
2320

2321
        // Before we attempt to sign the packet, ensure that every input either
2322
        // has a witness UTXO, or a non witness UTXO.
2323
        for idx := range packet.UnsignedTx.TxIn {
6✔
2324
                in := packet.Inputs[idx]
3✔
2325

3✔
2326
                // Doesn't have either a witness or non witness UTXO so we need
3✔
2327
                // to exit here as otherwise signing will fail.
3✔
2328
                if in.WitnessUtxo == nil && in.NonWitnessUtxo == nil {
6✔
2329
                        return nil, fmt.Errorf("input (index=%v) doesn't "+
3✔
2330
                                "specify any UTXO info", idx)
3✔
2331
                }
3✔
2332
        }
2333

2334
        // Let the wallet do the heavy lifting. This will sign all inputs that
2335
        // we have the UTXO for. If some inputs can't be signed and don't have
2336
        // witness data attached, they will just be skipped.
2337
        signedInputs, err := w.cfg.Wallet.SignPsbt(packet)
3✔
2338
        if err != nil {
3✔
2339
                return nil, fmt.Errorf("error signing PSBT: %w", err)
×
2340
        }
×
2341

2342
        // Serialize the signed PSBT in both the packet and wire format.
2343
        var signedPsbtBytes bytes.Buffer
3✔
2344
        err = packet.Serialize(&signedPsbtBytes)
3✔
2345
        if err != nil {
3✔
2346
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
2347
        }
×
2348

2349
        return &SignPsbtResponse{
3✔
2350
                SignedPsbt:   signedPsbtBytes.Bytes(),
3✔
2351
                SignedInputs: signedInputs,
3✔
2352
        }, nil
3✔
2353
}
2354

2355
// FinalizePsbt expects a partial transaction with all inputs and outputs fully
2356
// declared and tries to sign all inputs that belong to the wallet. Lnd must be
2357
// the last signer of the transaction. That means, if there are any unsigned
2358
// non-witness inputs or inputs without UTXO information attached or inputs
2359
// without witness data that do not belong to lnd's wallet, this method will
2360
// fail. If no error is returned, the PSBT is ready to be extracted and the
2361
// final TX within to be broadcast.
2362
//
2363
// NOTE: This method does NOT publish the transaction once finalized. It is the
2364
// caller's responsibility to either publish the transaction on success or
2365
// unlock/release any locked UTXOs in case of an error in this method.
2366
func (w *WalletKit) FinalizePsbt(_ context.Context,
2367
        req *FinalizePsbtRequest) (*FinalizePsbtResponse, error) {
3✔
2368

3✔
2369
        // We'll assume the PSBT was funded by the default account unless
3✔
2370
        // otherwise specified.
3✔
2371
        account := lnwallet.DefaultAccountName
3✔
2372
        if req.Account != "" {
3✔
2373
                account = req.Account
×
2374
        }
×
2375

2376
        // Parse the funded PSBT.
2377
        packet, err := psbt.NewFromRawBytes(
3✔
2378
                bytes.NewReader(req.FundedPsbt), false,
3✔
2379
        )
3✔
2380
        if err != nil {
3✔
2381
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
2382
        }
×
2383

2384
        // The only check done at this level is to validate that the PSBT is
2385
        // not complete. The wallet performs all other checks.
2386
        if packet.IsComplete() {
3✔
2387
                return nil, fmt.Errorf("PSBT is already fully signed")
×
2388
        }
×
2389

2390
        // Let the wallet do the heavy lifting. This will sign all inputs that
2391
        // we have the UTXO for. If some inputs can't be signed and don't have
2392
        // witness data attached, this will fail.
2393
        err = w.cfg.Wallet.FinalizePsbt(packet, account)
3✔
2394
        if err != nil {
3✔
2395
                return nil, fmt.Errorf("error finalizing PSBT: %w", err)
×
2396
        }
×
2397

2398
        var (
3✔
2399
                finalPsbtBytes bytes.Buffer
3✔
2400
                finalTxBytes   bytes.Buffer
3✔
2401
        )
3✔
2402

3✔
2403
        // Serialize the finalized PSBT in both the packet and wire format.
3✔
2404
        err = packet.Serialize(&finalPsbtBytes)
3✔
2405
        if err != nil {
3✔
2406
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
2407
        }
×
2408
        finalTx, err := psbt.Extract(packet)
3✔
2409
        if err != nil {
3✔
2410
                return nil, fmt.Errorf("unable to extract final TX: %w", err)
×
2411
        }
×
2412
        err = finalTx.Serialize(&finalTxBytes)
3✔
2413
        if err != nil {
3✔
2414
                return nil, fmt.Errorf("error serializing final TX: %w", err)
×
2415
        }
×
2416

2417
        return &FinalizePsbtResponse{
3✔
2418
                SignedPsbt: finalPsbtBytes.Bytes(),
3✔
2419
                RawFinalTx: finalTxBytes.Bytes(),
3✔
2420
        }, nil
3✔
2421
}
2422

2423
// marshalWalletAccount converts the properties of an account into its RPC
2424
// representation.
2425
func marshalWalletAccount(internalScope waddrmgr.KeyScope,
2426
        account *waddrmgr.AccountProperties) (*Account, error) {
3✔
2427

3✔
2428
        var addrType AddressType
3✔
2429
        switch account.KeyScope {
3✔
2430
        case waddrmgr.KeyScopeBIP0049Plus:
3✔
2431
                // No address schema present represents the traditional BIP-0049
3✔
2432
                // address derivation scheme.
3✔
2433
                if account.AddrSchema == nil {
6✔
2434
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
3✔
2435
                        break
3✔
2436
                }
2437

2438
                switch *account.AddrSchema {
3✔
2439
                case waddrmgr.KeyScopeBIP0049AddrSchema:
3✔
2440
                        addrType = AddressType_NESTED_WITNESS_PUBKEY_HASH
3✔
2441

2442
                case waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0049Plus]:
3✔
2443
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
3✔
2444

2445
                default:
×
2446
                        return nil, fmt.Errorf("unsupported address schema %v",
×
2447
                                *account.AddrSchema)
×
2448
                }
2449

2450
        case waddrmgr.KeyScopeBIP0084:
3✔
2451
                addrType = AddressType_WITNESS_PUBKEY_HASH
3✔
2452

2453
        case waddrmgr.KeyScopeBIP0086:
3✔
2454
                addrType = AddressType_TAPROOT_PUBKEY
3✔
2455

2456
        case internalScope:
3✔
2457
                addrType = AddressType_WITNESS_PUBKEY_HASH
3✔
2458

2459
        default:
×
2460
                return nil, fmt.Errorf("account %v has unsupported "+
×
2461
                        "key scope %v", account.AccountName, account.KeyScope)
×
2462
        }
2463

2464
        rpcAccount := &Account{
3✔
2465
                Name:             account.AccountName,
3✔
2466
                AddressType:      addrType,
3✔
2467
                ExternalKeyCount: account.ExternalKeyCount,
3✔
2468
                InternalKeyCount: account.InternalKeyCount,
3✔
2469
                WatchOnly:        account.IsWatchOnly,
3✔
2470
        }
3✔
2471

3✔
2472
        // The remaining fields can only be done on accounts other than the
3✔
2473
        // default imported one existing within each key scope.
3✔
2474
        if account.AccountName != waddrmgr.ImportedAddrAccountName {
6✔
2475
                nonHardenedIndex := account.AccountPubKey.ChildIndex() -
3✔
2476
                        hdkeychain.HardenedKeyStart
3✔
2477
                rpcAccount.ExtendedPublicKey = account.AccountPubKey.String()
3✔
2478
                if account.MasterKeyFingerprint != 0 {
3✔
2479
                        var mkfp [4]byte
×
2480
                        binary.BigEndian.PutUint32(
×
2481
                                mkfp[:], account.MasterKeyFingerprint,
×
2482
                        )
×
2483
                        rpcAccount.MasterKeyFingerprint = mkfp[:]
×
2484
                }
×
2485
                rpcAccount.DerivationPath = fmt.Sprintf("%v/%v'",
3✔
2486
                        account.KeyScope, nonHardenedIndex)
3✔
2487
        }
2488

2489
        return rpcAccount, nil
3✔
2490
}
2491

2492
// marshalWalletAddressList converts the list of address into its RPC
2493
// representation.
2494
func marshalWalletAddressList(w *WalletKit, account *waddrmgr.AccountProperties,
2495
        addressList []lnwallet.AddressProperty) (*AccountWithAddresses, error) {
3✔
2496

3✔
2497
        // Get the RPC representation of account.
3✔
2498
        rpcAccount, err := marshalWalletAccount(
3✔
2499
                w.internalScope(), account,
3✔
2500
        )
3✔
2501
        if err != nil {
3✔
2502
                return nil, err
×
2503
        }
×
2504

2505
        addresses := make([]*AddressProperty, len(addressList))
3✔
2506
        for idx, addr := range addressList {
6✔
2507
                var pubKeyBytes []byte
3✔
2508
                if addr.PublicKey != nil {
6✔
2509
                        pubKeyBytes = addr.PublicKey.SerializeCompressed()
3✔
2510
                }
3✔
2511
                addresses[idx] = &AddressProperty{
3✔
2512
                        Address:        addr.Address,
3✔
2513
                        IsInternal:     addr.Internal,
3✔
2514
                        Balance:        int64(addr.Balance),
3✔
2515
                        DerivationPath: addr.DerivationPath,
3✔
2516
                        PublicKey:      pubKeyBytes,
3✔
2517
                }
3✔
2518
        }
2519

2520
        rpcAddressList := &AccountWithAddresses{
3✔
2521
                Name:           rpcAccount.Name,
3✔
2522
                AddressType:    rpcAccount.AddressType,
3✔
2523
                DerivationPath: rpcAccount.DerivationPath,
3✔
2524
                Addresses:      addresses,
3✔
2525
        }
3✔
2526

3✔
2527
        return rpcAddressList, nil
3✔
2528
}
2529

2530
// ListAccounts retrieves all accounts belonging to the wallet by default. A
2531
// name and key scope filter can be provided to filter through all of the wallet
2532
// accounts and return only those matching.
2533
func (w *WalletKit) ListAccounts(ctx context.Context,
2534
        req *ListAccountsRequest) (*ListAccountsResponse, error) {
3✔
2535

3✔
2536
        // Map the supported address types into their corresponding key scope.
3✔
2537
        var keyScopeFilter *waddrmgr.KeyScope
3✔
2538
        switch req.AddressType {
3✔
2539
        case AddressType_UNKNOWN:
3✔
2540
                break
3✔
2541

2542
        case AddressType_WITNESS_PUBKEY_HASH:
3✔
2543
                keyScope := waddrmgr.KeyScopeBIP0084
3✔
2544
                keyScopeFilter = &keyScope
3✔
2545

2546
        case AddressType_NESTED_WITNESS_PUBKEY_HASH,
2547
                AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
3✔
2548

3✔
2549
                keyScope := waddrmgr.KeyScopeBIP0049Plus
3✔
2550
                keyScopeFilter = &keyScope
3✔
2551

2552
        case AddressType_TAPROOT_PUBKEY:
3✔
2553
                keyScope := waddrmgr.KeyScopeBIP0086
3✔
2554
                keyScopeFilter = &keyScope
3✔
2555

2556
        default:
×
2557
                return nil, fmt.Errorf("unhandled address type %v",
×
2558
                        req.AddressType)
×
2559
        }
2560

2561
        accounts, err := w.cfg.Wallet.ListAccounts(req.Name, keyScopeFilter)
3✔
2562
        if err != nil {
3✔
2563
                return nil, err
×
2564
        }
×
2565

2566
        rpcAccounts := make([]*Account, 0, len(accounts))
3✔
2567
        for _, account := range accounts {
6✔
2568
                // Don't include the default imported accounts created by the
3✔
2569
                // wallet in the response if they don't have any keys imported.
3✔
2570
                if account.AccountName == waddrmgr.ImportedAddrAccountName &&
3✔
2571
                        account.ImportedKeyCount == 0 {
6✔
2572

3✔
2573
                        continue
3✔
2574
                }
2575

2576
                rpcAccount, err := marshalWalletAccount(
3✔
2577
                        w.internalScope(), account,
3✔
2578
                )
3✔
2579
                if err != nil {
3✔
2580
                        return nil, err
×
2581
                }
×
2582
                rpcAccounts = append(rpcAccounts, rpcAccount)
3✔
2583
        }
2584

2585
        return &ListAccountsResponse{Accounts: rpcAccounts}, nil
3✔
2586
}
2587

2588
// RequiredReserve returns the minimum amount of satoshis that should be
2589
// kept in the wallet in order to fee bump anchor channels if necessary.
2590
// The value scales with the number of public anchor channels but is
2591
// capped at a maximum.
2592
func (w *WalletKit) RequiredReserve(ctx context.Context,
2593
        req *RequiredReserveRequest) (*RequiredReserveResponse, error) {
3✔
2594

3✔
2595
        numAnchorChans, err := w.cfg.CurrentNumAnchorChans()
3✔
2596
        if err != nil {
3✔
2597
                return nil, err
×
2598
        }
×
2599

2600
        additionalChans := req.AdditionalPublicChannels
3✔
2601
        totalChans := uint32(numAnchorChans) + additionalChans
3✔
2602
        reserved := w.cfg.Wallet.RequiredReserve(totalChans)
3✔
2603

3✔
2604
        return &RequiredReserveResponse{
3✔
2605
                RequiredReserve: int64(reserved),
3✔
2606
        }, nil
3✔
2607
}
2608

2609
// ListAddresses retrieves all the addresses along with their balance. An
2610
// account name filter can be provided to filter through all of the
2611
// wallet accounts and return the addresses of only those matching.
2612
func (w *WalletKit) ListAddresses(ctx context.Context,
2613
        req *ListAddressesRequest) (*ListAddressesResponse, error) {
3✔
2614

3✔
2615
        addressLists, err := w.cfg.Wallet.ListAddresses(
3✔
2616
                req.AccountName,
3✔
2617
                req.ShowCustomAccounts,
3✔
2618
        )
3✔
2619
        if err != nil {
3✔
2620
                return nil, err
×
2621
        }
×
2622

2623
        // Create a slice of accounts from addressLists map.
2624
        accounts := make([]*waddrmgr.AccountProperties, 0, len(addressLists))
3✔
2625
        for account := range addressLists {
6✔
2626
                accounts = append(accounts, account)
3✔
2627
        }
3✔
2628

2629
        // Sort the accounts by derivation path.
2630
        sort.Slice(accounts, func(i, j int) bool {
6✔
2631
                scopeI := accounts[i].KeyScope
3✔
2632
                scopeJ := accounts[j].KeyScope
3✔
2633
                if scopeI.Purpose == scopeJ.Purpose {
3✔
2634
                        if scopeI.Coin == scopeJ.Coin {
×
2635
                                acntNumI := accounts[i].AccountNumber
×
2636
                                acntNumJ := accounts[j].AccountNumber
×
2637
                                return acntNumI < acntNumJ
×
2638
                        }
×
2639

2640
                        return scopeI.Coin < scopeJ.Coin
×
2641
                }
2642

2643
                return scopeI.Purpose < scopeJ.Purpose
3✔
2644
        })
2645

2646
        rpcAddressLists := make([]*AccountWithAddresses, 0, len(addressLists))
3✔
2647
        for _, account := range accounts {
6✔
2648
                addressList := addressLists[account]
3✔
2649
                rpcAddressList, err := marshalWalletAddressList(
3✔
2650
                        w, account, addressList,
3✔
2651
                )
3✔
2652
                if err != nil {
3✔
2653
                        return nil, err
×
2654
                }
×
2655

2656
                rpcAddressLists = append(rpcAddressLists, rpcAddressList)
3✔
2657
        }
2658

2659
        return &ListAddressesResponse{
3✔
2660
                AccountWithAddresses: rpcAddressLists,
3✔
2661
        }, nil
3✔
2662
}
2663

2664
// parseAddrType parses an address type from its RPC representation to a
2665
// *waddrmgr.AddressType.
2666
func parseAddrType(addrType AddressType,
2667
        required bool) (*waddrmgr.AddressType, error) {
3✔
2668

3✔
2669
        switch addrType {
3✔
2670
        case AddressType_UNKNOWN:
×
2671
                if required {
×
2672
                        return nil, fmt.Errorf("an address type must be " +
×
2673
                                "specified")
×
2674
                }
×
2675
                return nil, nil
×
2676

2677
        case AddressType_WITNESS_PUBKEY_HASH:
3✔
2678
                addrTyp := waddrmgr.WitnessPubKey
3✔
2679
                return &addrTyp, nil
3✔
2680

2681
        case AddressType_NESTED_WITNESS_PUBKEY_HASH:
3✔
2682
                addrTyp := waddrmgr.NestedWitnessPubKey
3✔
2683
                return &addrTyp, nil
3✔
2684

2685
        case AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
3✔
2686
                addrTyp := waddrmgr.WitnessPubKey
3✔
2687
                return &addrTyp, nil
3✔
2688

2689
        case AddressType_TAPROOT_PUBKEY:
3✔
2690
                addrTyp := waddrmgr.TaprootPubKey
3✔
2691
                return &addrTyp, nil
3✔
2692

2693
        default:
×
2694
                return nil, fmt.Errorf("unhandled address type %v", addrType)
×
2695
        }
2696
}
2697

2698
// msgSignaturePrefix is a prefix used to prevent inadvertently signing a
2699
// transaction or a signature. It is prepended in front of the message and
2700
// follows the same standard as bitcoin core and btcd.
2701
const msgSignaturePrefix = "Bitcoin Signed Message:\n"
2702

2703
// SignMessageWithAddr signs a message with the private key of the provided
2704
// address. The address needs to belong to the lnd wallet.
2705
func (w *WalletKit) SignMessageWithAddr(_ context.Context,
2706
        req *SignMessageWithAddrRequest) (*SignMessageWithAddrResponse, error) {
3✔
2707

3✔
2708
        addr, err := btcutil.DecodeAddress(req.Addr, w.cfg.ChainParams)
3✔
2709
        if err != nil {
3✔
2710
                return nil, fmt.Errorf("unable to decode address: %w", err)
×
2711
        }
×
2712

2713
        if !addr.IsForNet(w.cfg.ChainParams) {
3✔
2714
                return nil, fmt.Errorf("encoded address is for "+
×
2715
                        "the wrong network %s", req.Addr)
×
2716
        }
×
2717

2718
        // Fetch address infos from own wallet and check whether it belongs
2719
        // to the lnd wallet.
2720
        managedAddr, err := w.cfg.Wallet.AddressInfo(addr)
3✔
2721
        if err != nil {
3✔
2722
                return nil, fmt.Errorf("address could not be found in the "+
×
2723
                        "wallet database: %w", err)
×
2724
        }
×
2725

2726
        // Verifying by checking the interface type that the wallet knows about
2727
        // the public and private keys so it can sign the message with the
2728
        // private key of this address.
2729
        pubKey, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
3✔
2730
        if !ok {
3✔
2731
                return nil, fmt.Errorf("private key to address is unknown")
×
2732
        }
×
2733

2734
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
3✔
2735
        if err != nil {
3✔
2736
                return nil, err
×
2737
        }
×
2738

2739
        // For all address types (P2WKH, NP2WKH,P2TR) the ECDSA compact signing
2740
        // algorithm is used. For P2TR addresses this represents a special case.
2741
        // ECDSA is used to create a compact signature which makes the public
2742
        // key of the signature recoverable. For Schnorr no known compact
2743
        // signing algorithm exists yet.
2744
        privKey, err := pubKey.PrivKey()
3✔
2745
        if err != nil {
3✔
2746
                return nil, fmt.Errorf("no private key could be "+
×
2747
                        "fetched from wallet database: %w", err)
×
2748
        }
×
2749

2750
        sigBytes := ecdsa.SignCompact(privKey, digest, pubKey.Compressed())
3✔
2751

3✔
2752
        // Bitcoin signatures are base64 encoded (being compatible with
3✔
2753
        // bitcoin-core and btcd).
3✔
2754
        sig := base64.StdEncoding.EncodeToString(sigBytes)
3✔
2755

3✔
2756
        return &SignMessageWithAddrResponse{
3✔
2757
                Signature: sig,
3✔
2758
        }, nil
3✔
2759
}
2760

2761
// VerifyMessageWithAddr verifies a signature on a message with a provided
2762
// address, it checks both the validity of the signature itself and then
2763
// verifies whether the signature corresponds to the public key of the
2764
// provided address. There is no dependence on the private key of the address
2765
// therefore also external addresses are allowed to verify signatures.
2766
// Supported address types are P2PKH, P2WKH, NP2WKH, P2TR.
2767
func (w *WalletKit) VerifyMessageWithAddr(_ context.Context,
2768
        req *VerifyMessageWithAddrRequest) (*VerifyMessageWithAddrResponse,
2769
        error) {
3✔
2770

3✔
2771
        sig, err := base64.StdEncoding.DecodeString(req.Signature)
3✔
2772
        if err != nil {
3✔
2773
                return nil, fmt.Errorf("malformed base64 encoding of "+
×
2774
                        "the signature: %w", err)
×
2775
        }
×
2776

2777
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
3✔
2778
        if err != nil {
3✔
2779
                return nil, err
×
2780
        }
×
2781

2782
        pk, wasCompressed, err := ecdsa.RecoverCompact(sig, digest)
3✔
2783
        if err != nil {
3✔
2784
                return nil, fmt.Errorf("unable to recover public key "+
×
2785
                        "from compact signature: %w", err)
×
2786
        }
×
2787

2788
        var serializedPubkey []byte
3✔
2789
        if wasCompressed {
6✔
2790
                serializedPubkey = pk.SerializeCompressed()
3✔
2791
        } else {
3✔
2792
                serializedPubkey = pk.SerializeUncompressed()
×
2793
        }
×
2794

2795
        addr, err := btcutil.DecodeAddress(req.Addr, w.cfg.ChainParams)
3✔
2796
        if err != nil {
3✔
2797
                return nil, fmt.Errorf("unable to decode address: %w", err)
×
2798
        }
×
2799

2800
        if !addr.IsForNet(w.cfg.ChainParams) {
3✔
2801
                return nil, fmt.Errorf("encoded address is for"+
×
2802
                        "the wrong network %s", req.Addr)
×
2803
        }
×
2804

2805
        var (
3✔
2806
                address    btcutil.Address
3✔
2807
                pubKeyHash = btcutil.Hash160(serializedPubkey)
3✔
2808
        )
3✔
2809

3✔
2810
        // Ensure the address is one of the supported types.
3✔
2811
        switch addr.(type) {
3✔
2812
        case *btcutil.AddressPubKeyHash:
3✔
2813
                address, err = btcutil.NewAddressPubKeyHash(
3✔
2814
                        pubKeyHash, w.cfg.ChainParams,
3✔
2815
                )
3✔
2816
                if err != nil {
3✔
2817
                        return nil, err
×
2818
                }
×
2819

2820
        case *btcutil.AddressWitnessPubKeyHash:
3✔
2821
                address, err = btcutil.NewAddressWitnessPubKeyHash(
3✔
2822
                        pubKeyHash, w.cfg.ChainParams,
3✔
2823
                )
3✔
2824
                if err != nil {
3✔
2825
                        return nil, err
×
2826
                }
×
2827

2828
        case *btcutil.AddressScriptHash:
3✔
2829
                // Check if address is a Nested P2WKH (NP2WKH).
3✔
2830
                address, err = btcutil.NewAddressWitnessPubKeyHash(
3✔
2831
                        pubKeyHash, w.cfg.ChainParams,
3✔
2832
                )
3✔
2833
                if err != nil {
3✔
2834
                        return nil, err
×
2835
                }
×
2836

2837
                witnessScript, err := txscript.PayToAddrScript(address)
3✔
2838
                if err != nil {
3✔
2839
                        return nil, err
×
2840
                }
×
2841

2842
                address, err = btcutil.NewAddressScriptHashFromHash(
3✔
2843
                        btcutil.Hash160(witnessScript), w.cfg.ChainParams,
3✔
2844
                )
3✔
2845
                if err != nil {
3✔
2846
                        return nil, err
×
2847
                }
×
2848

2849
        case *btcutil.AddressTaproot:
3✔
2850
                // Only addresses without a tapscript are allowed because
3✔
2851
                // the verification is using the internal key.
3✔
2852
                tapKey := txscript.ComputeTaprootKeyNoScript(pk)
3✔
2853
                address, err = btcutil.NewAddressTaproot(
3✔
2854
                        schnorr.SerializePubKey(tapKey),
3✔
2855
                        w.cfg.ChainParams,
3✔
2856
                )
3✔
2857
                if err != nil {
3✔
2858
                        return nil, err
×
2859
                }
×
2860

2861
        default:
×
2862
                return nil, fmt.Errorf("unsupported address type")
×
2863
        }
2864

2865
        return &VerifyMessageWithAddrResponse{
3✔
2866
                Valid:  req.Addr == address.EncodeAddress(),
3✔
2867
                Pubkey: serializedPubkey,
3✔
2868
        }, nil
3✔
2869
}
2870

2871
// ImportAccount imports an account backed by an account extended public key.
2872
// The master key fingerprint denotes the fingerprint of the root key
2873
// corresponding to the account public key (also known as the key with
2874
// derivation path m/). This may be required by some hardware wallets for proper
2875
// identification and signing.
2876
//
2877
// The address type can usually be inferred from the key's version, but may be
2878
// required for certain keys to map them into the proper scope.
2879
//
2880
// For BIP-0044 keys, an address type must be specified as we intend to not
2881
// support importing BIP-0044 keys into the wallet using the legacy
2882
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force
2883
// the standard BIP-0049 derivation scheme, while a witness address type will
2884
// force the standard BIP-0084 derivation scheme.
2885
//
2886
// For BIP-0049 keys, an address type must also be specified to make a
2887
// distinction between the standard BIP-0049 address schema (nested witness
2888
// pubkeys everywhere) and our own BIP-0049Plus address schema (nested pubkeys
2889
// externally, witness pubkeys internally).
2890
func (w *WalletKit) ImportAccount(_ context.Context,
2891
        req *ImportAccountRequest) (*ImportAccountResponse, error) {
3✔
2892

3✔
2893
        accountPubKey, err := hdkeychain.NewKeyFromString(req.ExtendedPublicKey)
3✔
2894
        if err != nil {
3✔
2895
                return nil, err
×
2896
        }
×
2897

2898
        var mkfp uint32
3✔
2899
        switch len(req.MasterKeyFingerprint) {
3✔
2900
        // No master key fingerprint provided, which is fine as it's not
2901
        // required.
2902
        case 0:
3✔
2903
        // Expected length.
2904
        case 4:
×
2905
                mkfp = binary.BigEndian.Uint32(req.MasterKeyFingerprint)
×
2906
        default:
×
2907
                return nil, errors.New("invalid length for master key " +
×
2908
                        "fingerprint, expected 4 bytes in big-endian")
×
2909
        }
2910

2911
        addrType, err := parseAddrType(req.AddressType, false)
3✔
2912
        if err != nil {
3✔
2913
                return nil, err
×
2914
        }
×
2915

2916
        accountProps, extAddrs, intAddrs, err := w.cfg.Wallet.ImportAccount(
3✔
2917
                req.Name, accountPubKey, mkfp, addrType, req.DryRun,
3✔
2918
        )
3✔
2919
        if err != nil {
6✔
2920
                return nil, err
3✔
2921
        }
3✔
2922

2923
        rpcAccount, err := marshalWalletAccount(w.internalScope(), accountProps)
3✔
2924
        if err != nil {
3✔
2925
                return nil, err
×
2926
        }
×
2927

2928
        resp := &ImportAccountResponse{Account: rpcAccount}
3✔
2929
        if !req.DryRun {
6✔
2930
                return resp, nil
3✔
2931
        }
3✔
2932

2933
        resp.DryRunExternalAddrs = make([]string, len(extAddrs))
×
2934
        for i := 0; i < len(extAddrs); i++ {
×
2935
                resp.DryRunExternalAddrs[i] = extAddrs[i].String()
×
2936
        }
×
2937
        resp.DryRunInternalAddrs = make([]string, len(intAddrs))
×
2938
        for i := 0; i < len(intAddrs); i++ {
×
2939
                resp.DryRunInternalAddrs[i] = intAddrs[i].String()
×
2940
        }
×
2941

2942
        return resp, nil
×
2943
}
2944

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

3✔
2955
        var (
3✔
2956
                pubKey *btcec.PublicKey
3✔
2957
                err    error
3✔
2958
        )
3✔
2959
        switch req.AddressType {
3✔
2960
        case AddressType_TAPROOT_PUBKEY:
3✔
2961
                pubKey, err = schnorr.ParsePubKey(req.PublicKey)
3✔
2962

2963
        default:
3✔
2964
                pubKey, err = btcec.ParsePubKey(req.PublicKey)
3✔
2965
        }
2966
        if err != nil {
3✔
2967
                return nil, err
×
2968
        }
×
2969

2970
        addrType, err := parseAddrType(req.AddressType, true)
3✔
2971
        if err != nil {
3✔
2972
                return nil, err
×
2973
        }
×
2974

2975
        if err := w.cfg.Wallet.ImportPublicKey(pubKey, *addrType); err != nil {
3✔
2976
                return nil, err
×
2977
        }
×
2978

2979
        return &ImportPublicKeyResponse{
3✔
2980
                Status: fmt.Sprintf("public key %x imported",
3✔
2981
                        pubKey.SerializeCompressed()),
3✔
2982
        }, nil
3✔
2983
}
2984

2985
// ImportTapscript imports a Taproot script and internal key and adds the
2986
// resulting Taproot output key as a watch-only output script into the wallet.
2987
// For BIP-0086 style Taproot keys (no root hash commitment and no script spend
2988
// path) use ImportPublicKey.
2989
//
2990
// NOTE: Taproot keys imported through this RPC currently _cannot_ be used for
2991
// funding PSBTs. Only tracking the balance and UTXOs is currently supported.
2992
func (w *WalletKit) ImportTapscript(_ context.Context,
2993
        req *ImportTapscriptRequest) (*ImportTapscriptResponse, error) {
3✔
2994

3✔
2995
        internalKey, err := schnorr.ParsePubKey(req.InternalPublicKey)
3✔
2996
        if err != nil {
3✔
2997
                return nil, fmt.Errorf("error parsing internal key: %w", err)
×
2998
        }
×
2999

3000
        var tapscript *waddrmgr.Tapscript
3✔
3001
        switch {
3✔
3002
        case req.GetFullTree() != nil:
3✔
3003
                tree := req.GetFullTree()
3✔
3004
                leaves := make([]txscript.TapLeaf, len(tree.AllLeaves))
3✔
3005
                for idx, leaf := range tree.AllLeaves {
6✔
3006
                        leaves[idx] = txscript.TapLeaf{
3✔
3007
                                LeafVersion: txscript.TapscriptLeafVersion(
3✔
3008
                                        leaf.LeafVersion,
3✔
3009
                                ),
3✔
3010
                                Script: leaf.Script,
3✔
3011
                        }
3✔
3012
                }
3✔
3013

3014
                tapscript = input.TapscriptFullTree(internalKey, leaves...)
3✔
3015

3016
        case req.GetPartialReveal() != nil:
3✔
3017
                partialReveal := req.GetPartialReveal()
3✔
3018
                if partialReveal.RevealedLeaf == nil {
3✔
3019
                        return nil, fmt.Errorf("missing revealed leaf")
×
3020
                }
×
3021

3022
                revealedLeaf := txscript.TapLeaf{
3✔
3023
                        LeafVersion: txscript.TapscriptLeafVersion(
3✔
3024
                                partialReveal.RevealedLeaf.LeafVersion,
3✔
3025
                        ),
3✔
3026
                        Script: partialReveal.RevealedLeaf.Script,
3✔
3027
                }
3✔
3028
                if len(partialReveal.FullInclusionProof)%32 != 0 {
3✔
3029
                        return nil, fmt.Errorf("invalid inclusion proof "+
×
3030
                                "length, expected multiple of 32, got %d",
×
3031
                                len(partialReveal.FullInclusionProof)%32)
×
3032
                }
×
3033

3034
                tapscript = input.TapscriptPartialReveal(
3✔
3035
                        internalKey, revealedLeaf,
3✔
3036
                        partialReveal.FullInclusionProof,
3✔
3037
                )
3✔
3038

3039
        case req.GetRootHashOnly() != nil:
3✔
3040
                rootHash := req.GetRootHashOnly()
3✔
3041
                if len(rootHash) == 0 {
3✔
3042
                        return nil, fmt.Errorf("missing root hash")
×
3043
                }
×
3044

3045
                tapscript = input.TapscriptRootHashOnly(internalKey, rootHash)
3✔
3046

3047
        case req.GetFullKeyOnly():
3✔
3048
                tapscript = input.TapscriptFullKeyOnly(internalKey)
3✔
3049

3050
        default:
×
3051
                return nil, fmt.Errorf("invalid script")
×
3052
        }
3053

3054
        taprootScope := waddrmgr.KeyScopeBIP0086
3✔
3055
        addr, err := w.cfg.Wallet.ImportTaprootScript(taprootScope, tapscript)
3✔
3056
        if err != nil {
3✔
3057
                return nil, fmt.Errorf("error importing script into wallet: %w",
×
3058
                        err)
×
3059
        }
×
3060

3061
        return &ImportTapscriptResponse{
3✔
3062
                P2TrAddress: addr.Address().String(),
3✔
3063
        }, nil
3✔
3064
}
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