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

lightningnetwork / lnd / 12235114561

09 Dec 2024 11:56AM UTC coverage: 49.773% (-9.0%) from 58.805%
12235114561

push

github

web-flow
Merge pull request #9330 from ProofOfKeags/update/fn2

multi: update to fn v2

105 of 120 new or added lines in 16 files covered. (87.5%)

25489 existing lines in 427 files now uncovered.

100083 of 201077 relevant lines covered (49.77%)

2.07 hits per line

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

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

4
package walletrpc
5

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

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

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

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

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

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

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

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

256
        cfg *Config
257
}
258

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

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

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

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

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

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

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

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

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

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

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

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

4✔
346
        return nil
4✔
347
}
4✔
348

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

983
        var immediate bool
4✔
984
        switch {
4✔
985
        case in.Force && in.Immediate:
×
986
                return satPerKwOpt, false, fmt.Errorf("either Force or " +
×
987
                        "Immediate should be set, but not both")
×
988

989
        case in.Force:
×
990
                immediate = in.Force
×
991

992
        case in.Immediate:
4✔
993
                immediate = in.Immediate
4✔
994
        }
995

996
        return satPerKwOpt, immediate, nil
4✔
997
}
998

999
// prepareSweepParams creates the sweep params to be used for the sweeper. It
1000
// returns the new params and a bool indicating whether this is an existing
1001
// input.
1002
func (w *WalletKit) prepareSweepParams(in *BumpFeeRequest,
1003
        op wire.OutPoint, currentHeight int32) (sweep.Params, bool, error) {
4✔
1004

4✔
1005
        // Return an error if both deprecated and new fields are used.
4✔
1006
        feerate, immediate, err := validateBumpFeeRequest(in)
4✔
1007
        if err != nil {
4✔
1008
                return sweep.Params{}, false, err
×
1009
        }
×
1010

1011
        // Get the current pending inputs.
1012
        inputMap, err := w.cfg.Sweeper.PendingInputs()
4✔
1013
        if err != nil {
4✔
1014
                return sweep.Params{}, false, fmt.Errorf("unable to get "+
×
1015
                        "pending inputs: %w", err)
×
1016
        }
×
1017

1018
        // Find the pending input.
1019
        //
1020
        // TODO(yy): act differently based on the state of the input?
1021
        inp, ok := inputMap[op]
4✔
1022

4✔
1023
        if !ok {
7✔
1024
                // NOTE: if this input doesn't exist and the new budget is not
3✔
1025
                // specified, the params would have a zero budget.
3✔
1026
                params := sweep.Params{
3✔
1027
                        Immediate:       immediate,
3✔
1028
                        StartingFeeRate: feerate,
3✔
1029
                        Budget:          btcutil.Amount(in.Budget),
3✔
1030
                }
3✔
1031
                if in.TargetConf != 0 {
3✔
1032
                        params.DeadlineHeight = fn.Some(
×
1033
                                int32(in.TargetConf) + currentHeight,
×
1034
                        )
×
1035
                }
×
1036

1037
                return params, ok, nil
3✔
1038
        }
1039

1040
        // Find the existing budget used for this input. Note that this value
1041
        // must be greater than zero.
1042
        budget := inp.Params.Budget
4✔
1043

4✔
1044
        // Set the new budget if specified.
4✔
1045
        if in.Budget != 0 {
8✔
1046
                budget = btcutil.Amount(in.Budget)
4✔
1047
        }
4✔
1048

1049
        // For an existing input, we assign it first, then overwrite it if
1050
        // a deadline is requested.
1051
        deadline := inp.Params.DeadlineHeight
4✔
1052

4✔
1053
        // Set the deadline if target conf is specified.
4✔
1054
        //
4✔
1055
        // TODO(yy): upgrade `falafel` so we can make this field optional. Atm
4✔
1056
        // we cannot distinguish between user's not setting the field and
4✔
1057
        // setting it to 0.
4✔
1058
        if in.TargetConf != 0 {
8✔
1059
                deadline = fn.Some(int32(in.TargetConf) + currentHeight)
4✔
1060
        }
4✔
1061

1062
        // Prepare the new sweep params.
1063
        //
1064
        // NOTE: if this input doesn't exist and the new budget is not
1065
        // specified, the params would have a zero budget.
1066
        params := sweep.Params{
4✔
1067
                Immediate:       immediate,
4✔
1068
                StartingFeeRate: feerate,
4✔
1069
                DeadlineHeight:  deadline,
4✔
1070
                Budget:          budget,
4✔
1071
        }
4✔
1072

4✔
1073
        if ok {
8✔
1074
                log.Infof("[BumpFee]: bumping fee for existing input=%v, old "+
4✔
1075
                        "params=%v, new params=%v", op, inp.Params, params)
4✔
1076
        }
4✔
1077

1078
        return params, ok, nil
4✔
1079
}
1080

1081
// BumpFee allows bumping the fee rate of an arbitrary input. A fee preference
1082
// can be expressed either as a specific fee rate or a delta of blocks in which
1083
// the output should be swept on-chain within. If a fee preference is not
1084
// explicitly specified, then an error is returned. The status of the input
1085
// sweep can be checked through the PendingSweeps RPC.
1086
func (w *WalletKit) BumpFee(ctx context.Context,
1087
        in *BumpFeeRequest) (*BumpFeeResponse, error) {
4✔
1088

4✔
1089
        // Parse the outpoint from the request.
4✔
1090
        op, err := UnmarshallOutPoint(in.Outpoint)
4✔
1091
        if err != nil {
4✔
1092
                return nil, err
×
1093
        }
×
1094

1095
        // Get the current height so we can calculate the deadline height.
1096
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
4✔
1097
        if err != nil {
4✔
1098
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
1099
                        err)
×
1100
        }
×
1101

1102
        // We now create a new sweeping params and update it in the sweeper.
1103
        // This will complicate the RBF conditions if this input has already
1104
        // been offered to sweeper before and it has already been included in a
1105
        // tx with other inputs. If this is the case, two results are possible:
1106
        // - either this input successfully RBFed the existing tx, or,
1107
        // - the budget of this input was not enough to RBF the existing tx.
1108
        params, existing, err := w.prepareSweepParams(in, *op, currentHeight)
4✔
1109
        if err != nil {
4✔
1110
                return nil, err
×
1111
        }
×
1112

1113
        // If this input exists, we will update its params.
1114
        if existing {
8✔
1115
                _, err = w.cfg.Sweeper.UpdateParams(*op, params)
4✔
1116
                if err != nil {
4✔
1117
                        return nil, err
×
1118
                }
×
1119

1120
                return &BumpFeeResponse{
4✔
1121
                        Status: "Successfully registered rbf-tx with sweeper",
4✔
1122
                }, nil
4✔
1123
        }
1124

1125
        // Otherwise, create a new sweeping request for this input.
1126
        err = w.sweepNewInput(op, uint32(currentHeight), params)
3✔
1127
        if err != nil {
3✔
1128
                return nil, err
×
1129
        }
×
1130

1131
        return &BumpFeeResponse{
3✔
1132
                Status: "Successfully registered CPFP-tx with the sweeper",
3✔
1133
        }, nil
3✔
1134
}
1135

1136
// getWaitingCloseChannel returns the waiting close channel in case it does
1137
// exist in the underlying channel state database.
1138
func (w *WalletKit) getWaitingCloseChannel(
1139
        chanPoint wire.OutPoint) (*channeldb.OpenChannel, error) {
3✔
1140

3✔
1141
        // Fetch all channels, which still have their commitment transaction not
3✔
1142
        // confirmed (waiting close channels).
3✔
1143
        chans, err := w.cfg.ChanStateDB.FetchWaitingCloseChannels()
3✔
1144
        if err != nil {
3✔
1145
                return nil, err
×
1146
        }
×
1147

1148
        channel := fn.Find(chans, func(c *channeldb.OpenChannel) bool {
6✔
1149
                return c.FundingOutpoint == chanPoint
3✔
1150
        })
3✔
1151

1152
        return channel.UnwrapOrErr(errors.New("channel not found"))
3✔
1153
}
1154

1155
// BumpForceCloseFee bumps the fee rate of an unconfirmed anchor channel. It
1156
// updates the new fee rate parameters with the sweeper subsystem. Additionally
1157
// it will try to create anchor cpfp transactions for all possible commitment
1158
// transactions (local, remote, remote-dangling) so depending on which
1159
// commitment is in the local mempool only one of them will succeed in being
1160
// broadcasted.
1161
func (w *WalletKit) BumpForceCloseFee(_ context.Context,
1162
        in *BumpForceCloseFeeRequest) (*BumpForceCloseFeeResponse, error) {
3✔
1163

3✔
1164
        if in.ChanPoint == nil {
3✔
1165
                return nil, fmt.Errorf("no chan_point provided")
×
1166
        }
×
1167

1168
        lnrpcOutpoint, err := lnrpc.GetChannelOutPoint(in.ChanPoint)
3✔
1169
        if err != nil {
3✔
1170
                return nil, err
×
1171
        }
×
1172

1173
        outPoint, err := UnmarshallOutPoint(lnrpcOutpoint)
3✔
1174
        if err != nil {
3✔
1175
                return nil, err
×
1176
        }
×
1177

1178
        // Get the relevant channel if it is in the waiting close state.
1179
        channel, err := w.getWaitingCloseChannel(*outPoint)
3✔
1180
        if err != nil {
3✔
1181
                return nil, err
×
1182
        }
×
1183

1184
        if !channel.ChanType.HasAnchors() {
3✔
1185
                return nil, fmt.Errorf("not able to bump the fee of a " +
×
1186
                        "non-anchor channel")
×
1187
        }
×
1188

1189
        // Match pending sweeps with commitments of the channel for which a bump
1190
        // is requested. Depending on the commitment state when force closing
1191
        // the channel we might have up to 3 commitments to consider when
1192
        // bumping the fee.
1193
        commitSet := fn.NewSet[chainhash.Hash]()
3✔
1194

3✔
1195
        if channel.LocalCommitment.CommitTx != nil {
6✔
1196
                localTxID := channel.LocalCommitment.CommitTx.TxHash()
3✔
1197
                commitSet.Add(localTxID)
3✔
1198
        }
3✔
1199

1200
        if channel.RemoteCommitment.CommitTx != nil {
6✔
1201
                remoteTxID := channel.RemoteCommitment.CommitTx.TxHash()
3✔
1202
                commitSet.Add(remoteTxID)
3✔
1203
        }
3✔
1204

1205
        // Check whether there was a dangling commitment at the time the channel
1206
        // was force closed.
1207
        remoteCommitDiff, err := channel.RemoteCommitChainTip()
3✔
1208
        if err != nil && !errors.Is(err, channeldb.ErrNoPendingCommit) {
3✔
1209
                return nil, err
×
1210
        }
×
1211

1212
        if remoteCommitDiff != nil {
3✔
1213
                hash := remoteCommitDiff.Commitment.CommitTx.TxHash()
×
1214
                commitSet.Add(hash)
×
1215
        }
×
1216

1217
        // Retrieve all of the outputs the UtxoSweeper is currently trying to
1218
        // sweep.
1219
        inputsMap, err := w.cfg.Sweeper.PendingInputs()
3✔
1220
        if err != nil {
3✔
1221
                return nil, err
×
1222
        }
×
1223

1224
        // Get the current height so we can calculate the deadline height.
1225
        _, currentHeight, err := w.cfg.Chain.GetBestBlock()
3✔
1226
        if err != nil {
3✔
1227
                return nil, fmt.Errorf("unable to retrieve current height: %w",
×
1228
                        err)
×
1229
        }
×
1230

1231
        pendingSweeps := maps.Values(inputsMap)
3✔
1232

3✔
1233
        // Discard everything except for the anchor sweeps.
3✔
1234
        anchors := fn.Filter(
3✔
1235
                pendingSweeps,
3✔
1236
                func(sweep *sweep.PendingInputResponse) bool {
6✔
1237
                        // Only filter for anchor inputs because these are the
3✔
1238
                        // only inputs which can be used to bump a closed
3✔
1239
                        // unconfirmed commitment transaction.
3✔
1240
                        isCommitAnchor := sweep.WitnessType ==
3✔
1241
                                input.CommitmentAnchor
3✔
1242
                        isTaprootSweepSpend := sweep.WitnessType ==
3✔
1243
                                input.TaprootAnchorSweepSpend
3✔
1244
                        if !isCommitAnchor && !isTaprootSweepSpend {
3✔
NEW
1245
                                return false
×
NEW
1246
                        }
×
1247

1248
                        return commitSet.Contains(sweep.OutPoint.Hash)
3✔
1249
                },
1250
        )
1251

1252
        if len(anchors) == 0 {
3✔
1253
                return nil, fmt.Errorf("unable to find pending anchor outputs")
×
1254
        }
×
1255

1256
        // Filter all relevant anchor sweeps and update the sweep request.
1257
        for _, anchor := range anchors {
6✔
1258
                // Anchor cpfp bump request are predictable because they are
3✔
1259
                // swept separately hence not batched with other sweeps (they
3✔
1260
                // are marked with the exclusive group flag). Bumping the fee
3✔
1261
                // rate does not create any conflicting fee bump conditions.
3✔
1262
                // Either the rbf requirements are met or the bump is rejected
3✔
1263
                // by the mempool rules.
3✔
1264
                params, existing, err := w.prepareSweepParams(
3✔
1265
                        &BumpFeeRequest{
3✔
1266
                                Outpoint:    lnrpcOutpoint,
3✔
1267
                                TargetConf:  in.DeadlineDelta,
3✔
1268
                                SatPerVbyte: in.StartingFeerate,
3✔
1269
                                Immediate:   in.Immediate,
3✔
1270
                                Budget:      in.Budget,
3✔
1271
                        }, anchor.OutPoint, currentHeight,
3✔
1272
                )
3✔
1273
                if err != nil {
3✔
1274
                        return nil, err
×
1275
                }
×
1276

1277
                // There might be the case when an anchor sweep is confirmed
1278
                // between fetching the pending sweeps and preparing the sweep
1279
                // params. We log this case and proceed.
1280
                if !existing {
3✔
1281
                        log.Errorf("Sweep anchor input(%v) not known to the " +
×
1282
                                "sweeper subsystem")
×
1283
                        continue
×
1284
                }
1285

1286
                _, err = w.cfg.Sweeper.UpdateParams(anchor.OutPoint, params)
3✔
1287
                if err != nil {
3✔
1288
                        return nil, err
×
1289
                }
×
1290
        }
1291

1292
        return &BumpForceCloseFeeResponse{
3✔
1293
                Status: "Successfully registered anchor-cpfp transaction to" +
3✔
1294
                        "bump channel force close transaction",
3✔
1295
        }, nil
3✔
1296
}
1297

1298
// sweepNewInput handles the case where an input is seen the first time by the
1299
// sweeper. It will fetch the output from the wallet and construct an input and
1300
// offer it to the sweeper.
1301
//
1302
// NOTE: if the budget is not set, the default budget ratio is used.
1303
func (w *WalletKit) sweepNewInput(op *wire.OutPoint, currentHeight uint32,
1304
        params sweep.Params) error {
3✔
1305

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

3✔
1308
        // Since the sweeper is not aware of the input, we'll assume the user
3✔
1309
        // is attempting to bump an unconfirmed transaction's fee rate by
3✔
1310
        // sweeping an output within it under control of the wallet with a
3✔
1311
        // higher fee rate. In this case, this will be a CPFP.
3✔
1312
        //
3✔
1313
        // We'll gather all of the information required by the UtxoSweeper in
3✔
1314
        // order to sweep the output.
3✔
1315
        utxo, err := w.cfg.Wallet.FetchOutpointInfo(op)
3✔
1316
        if err != nil {
3✔
1317
                return err
×
1318
        }
×
1319

1320
        // We're only able to bump the fee of unconfirmed transactions.
1321
        if utxo.Confirmations > 0 {
3✔
1322
                return errors.New("unable to bump fee of a confirmed " +
×
1323
                        "transaction")
×
1324
        }
×
1325

1326
        // If there's no budget set, use the default value.
1327
        if params.Budget == 0 {
6✔
1328
                params.Budget = utxo.Value.MulF64(
3✔
1329
                        contractcourt.DefaultBudgetRatio,
3✔
1330
                )
3✔
1331
        }
3✔
1332

1333
        signDesc := &input.SignDescriptor{
3✔
1334
                Output: &wire.TxOut{
3✔
1335
                        PkScript: utxo.PkScript,
3✔
1336
                        Value:    int64(utxo.Value),
3✔
1337
                },
3✔
1338
                HashType: txscript.SigHashAll,
3✔
1339
        }
3✔
1340

3✔
1341
        var witnessType input.WitnessType
3✔
1342
        switch utxo.AddressType {
3✔
1343
        case lnwallet.WitnessPubKey:
×
1344
                witnessType = input.WitnessKeyHash
×
1345
        case lnwallet.NestedWitnessPubKey:
×
1346
                witnessType = input.NestedWitnessKeyHash
×
1347
        case lnwallet.TaprootPubkey:
3✔
1348
                witnessType = input.TaprootPubKeySpend
3✔
1349
                signDesc.HashType = txscript.SigHashDefault
3✔
1350
        default:
×
1351
                return fmt.Errorf("unknown input witness %v", op)
×
1352
        }
1353

1354
        log.Infof("[BumpFee]: bumping fee for new input=%v, params=%v", op,
3✔
1355
                params)
3✔
1356

3✔
1357
        inp := input.NewBaseInput(op, witnessType, signDesc, currentHeight)
3✔
1358
        if _, err = w.cfg.Sweeper.SweepInput(inp, params); err != nil {
3✔
1359
                return err
×
1360
        }
×
1361

1362
        return nil
3✔
1363
}
1364

1365
// ListSweeps returns a list of the sweeps that our node has published.
1366
func (w *WalletKit) ListSweeps(ctx context.Context,
1367
        in *ListSweepsRequest) (*ListSweepsResponse, error) {
4✔
1368

4✔
1369
        sweeps, err := w.cfg.Sweeper.ListSweeps()
4✔
1370
        if err != nil {
4✔
1371
                return nil, err
×
1372
        }
×
1373

1374
        sweepTxns := make(map[string]bool)
4✔
1375
        for _, sweep := range sweeps {
8✔
1376
                sweepTxns[sweep.String()] = true
4✔
1377
        }
4✔
1378

1379
        // Some of our sweeps could have been replaced by fee, or dropped out
1380
        // of the mempool. Here, we lookup our wallet transactions so that we
1381
        // can match our list of sweeps against the list of transactions that
1382
        // the wallet is still tracking. Sweeps are currently always swept to
1383
        // the default wallet account.
1384
        txns, firstIdx, lastIdx, err := w.cfg.Wallet.ListTransactionDetails(
4✔
1385
                in.StartHeight, btcwallet.UnconfirmedHeight,
4✔
1386
                lnwallet.DefaultAccountName, 0, 0,
4✔
1387
        )
4✔
1388
        if err != nil {
4✔
1389
                return nil, err
×
1390
        }
×
1391

1392
        var (
4✔
1393
                txids     []string
4✔
1394
                txDetails []*lnwallet.TransactionDetail
4✔
1395
        )
4✔
1396

4✔
1397
        for _, tx := range txns {
8✔
1398
                _, ok := sweepTxns[tx.Hash.String()]
4✔
1399
                if !ok {
8✔
1400
                        continue
4✔
1401
                }
1402

1403
                // Add the txid or full tx details depending on whether we want
1404
                // verbose output or not.
1405
                if in.Verbose {
8✔
1406
                        txDetails = append(txDetails, tx)
4✔
1407
                } else {
8✔
1408
                        txids = append(txids, tx.Hash.String())
4✔
1409
                }
4✔
1410
        }
1411

1412
        if in.Verbose {
8✔
1413
                return &ListSweepsResponse{
4✔
1414
                        Sweeps: &ListSweepsResponse_TransactionDetails{
4✔
1415
                                TransactionDetails: lnrpc.RPCTransactionDetails(
4✔
1416
                                        txDetails, firstIdx, lastIdx,
4✔
1417
                                ),
4✔
1418
                        },
4✔
1419
                }, nil
4✔
1420
        }
4✔
1421

1422
        return &ListSweepsResponse{
4✔
1423
                Sweeps: &ListSweepsResponse_TransactionIds{
4✔
1424
                        TransactionIds: &ListSweepsResponse_TransactionIDs{
4✔
1425
                                TransactionIds: txids,
4✔
1426
                        },
4✔
1427
                },
4✔
1428
        }, nil
4✔
1429
}
1430

1431
// LabelTransaction adds a label to a transaction.
1432
func (w *WalletKit) LabelTransaction(ctx context.Context,
1433
        req *LabelTransactionRequest) (*LabelTransactionResponse, error) {
4✔
1434

4✔
1435
        // Check that the label provided in non-zero.
4✔
1436
        if len(req.Label) == 0 {
8✔
1437
                return nil, ErrZeroLabel
4✔
1438
        }
4✔
1439

1440
        // Validate the length of the non-zero label. We do not need to use the
1441
        // label returned here, because the original is non-zero so will not
1442
        // be replaced.
1443
        if _, err := labels.ValidateAPI(req.Label); err != nil {
4✔
1444
                return nil, err
×
1445
        }
×
1446

1447
        hash, err := chainhash.NewHash(req.Txid)
4✔
1448
        if err != nil {
4✔
1449
                return nil, err
×
1450
        }
×
1451

1452
        err = w.cfg.Wallet.LabelTransaction(*hash, req.Label, req.Overwrite)
4✔
1453

4✔
1454
        return &LabelTransactionResponse{
4✔
1455
                Status: fmt.Sprintf("transaction label '%s' added", req.Label),
4✔
1456
        }, err
4✔
1457
}
1458

1459
// FundPsbt creates a fully populated PSBT that contains enough inputs to fund
1460
// the outputs specified in the template. There are three ways a user can
1461
// specify what we call the template (a list of inputs and outputs to use in the
1462
// PSBT): Either as a PSBT packet directly with no coin selection (using the
1463
// legacy "psbt" field), a PSBT with advanced coin selection support (using the
1464
// new "coin_select" field) or as a raw RPC message (using the "raw" field).
1465
// The legacy "psbt" and "raw" modes, the following restrictions apply:
1466
//  1. If there are no inputs specified in the template, coin selection is
1467
//     performed automatically.
1468
//  2. If the template does contain any inputs, it is assumed that full coin
1469
//     selection happened externally and no additional inputs are added. If the
1470
//     specified inputs aren't enough to fund the outputs with the given fee
1471
//     rate, an error is returned.
1472
//
1473
// The new "coin_select" mode does not have these restrictions and allows the
1474
// user to specify a PSBT with inputs and outputs and still perform coin
1475
// selection on top of that.
1476
// For all modes this RPC requires any inputs that are specified to be locked by
1477
// the user (if they belong to this node in the first place).
1478
// After either selecting or verifying the inputs, all input UTXOs are locked
1479
// with an internal app ID. A custom address type for change can be specified
1480
// for default accounts and single imported public keys (only P2TR for now).
1481
// Otherwise, P2WPKH will be used by default. No custom address type should be
1482
// provided for custom accounts as we will always generate the change address
1483
// using the coin selection key scope.
1484
//
1485
// NOTE: If this method returns without an error, it is the caller's
1486
// responsibility to either spend the locked UTXOs (by finalizing and then
1487
// publishing the transaction) or to unlock/release the locked UTXOs in case of
1488
// an error on the caller's side.
1489
func (w *WalletKit) FundPsbt(_ context.Context,
1490
        req *FundPsbtRequest) (*FundPsbtResponse, error) {
4✔
1491

4✔
1492
        coinSelectionStrategy, err := lnrpc.UnmarshallCoinSelectionStrategy(
4✔
1493
                req.CoinSelectionStrategy, w.cfg.CoinSelectionStrategy,
4✔
1494
        )
4✔
1495
        if err != nil {
4✔
1496
                return nil, err
×
1497
        }
×
1498

1499
        // Determine the desired transaction fee.
1500
        var feeSatPerKW chainfee.SatPerKWeight
4✔
1501
        switch {
4✔
1502
        // Estimate the fee by the target number of blocks to confirmation.
1503
        case req.GetTargetConf() != 0:
×
1504
                targetConf := req.GetTargetConf()
×
1505
                if targetConf < 2 {
×
1506
                        return nil, fmt.Errorf("confirmation target must be " +
×
1507
                                "greater than 1")
×
1508
                }
×
1509

1510
                feeSatPerKW, err = w.cfg.FeeEstimator.EstimateFeePerKW(
×
1511
                        targetConf,
×
1512
                )
×
1513
                if err != nil {
×
1514
                        return nil, fmt.Errorf("could not estimate fee: %w",
×
1515
                                err)
×
1516
                }
×
1517

1518
        // Convert the fee to sat/kW from the specified sat/vByte.
1519
        case req.GetSatPerVbyte() != 0:
4✔
1520
                feeSatPerKW = chainfee.SatPerKVByte(
4✔
1521
                        req.GetSatPerVbyte() * 1000,
4✔
1522
                ).FeePerKWeight()
4✔
1523

1524
        case req.GetSatPerKw() != 0:
×
1525
                feeSatPerKW = chainfee.SatPerKWeight(req.GetSatPerKw())
×
1526

1527
        default:
×
1528
                return nil, fmt.Errorf("fee definition missing, need to " +
×
1529
                        "specify either target_conf, sat_per_vbyte or " +
×
1530
                        "sat_per_kw")
×
1531
        }
1532

1533
        // Then, we'll extract the minimum number of confirmations that each
1534
        // output we use to fund the transaction should satisfy.
1535
        minConfs, err := lnrpc.ExtractMinConfs(
4✔
1536
                req.GetMinConfs(), req.GetSpendUnconfirmed(),
4✔
1537
        )
4✔
1538
        if err != nil {
4✔
1539
                return nil, err
×
1540
        }
×
1541

1542
        // We'll assume the PSBT will be funded by the default account unless
1543
        // otherwise specified.
1544
        account := lnwallet.DefaultAccountName
4✔
1545
        if req.Account != "" {
8✔
1546
                account = req.Account
4✔
1547
        }
4✔
1548

1549
        // There are three ways a user can specify what we call the template (a
1550
        // list of inputs and outputs to use in the PSBT): Either as a PSBT
1551
        // packet directly with no coin selection, a PSBT with coin selection or
1552
        // as a special RPC message. Find out which one the user wants to use,
1553
        // they are mutually exclusive.
1554
        switch {
4✔
1555
        // The template is specified as a PSBT. All we have to do is parse it.
1556
        case req.GetPsbt() != nil:
4✔
1557
                r := bytes.NewReader(req.GetPsbt())
4✔
1558
                packet, err := psbt.NewFromRawBytes(r, false)
4✔
1559
                if err != nil {
4✔
1560
                        return nil, fmt.Errorf("could not parse PSBT: %w", err)
×
1561
                }
×
1562

1563
                // Run the actual funding process now, using the internal
1564
                // wallet.
1565
                return w.fundPsbtInternalWallet(
4✔
1566
                        account, keyScopeFromChangeAddressType(req.ChangeType),
4✔
1567
                        packet, minConfs, feeSatPerKW, coinSelectionStrategy,
4✔
1568
                )
4✔
1569

1570
        // The template is specified as a PSBT with the intention to perform
1571
        // coin selection even if inputs are already present.
1572
        case req.GetCoinSelect() != nil:
4✔
1573
                coinSelectRequest := req.GetCoinSelect()
4✔
1574
                r := bytes.NewReader(coinSelectRequest.Psbt)
4✔
1575
                packet, err := psbt.NewFromRawBytes(r, false)
4✔
1576
                if err != nil {
4✔
1577
                        return nil, fmt.Errorf("could not parse PSBT: %w", err)
×
1578
                }
×
1579

1580
                numOutputs := int32(len(packet.UnsignedTx.TxOut))
4✔
1581
                if numOutputs == 0 {
4✔
1582
                        return nil, fmt.Errorf("no outputs specified in " +
×
1583
                                "template")
×
1584
                }
×
1585

1586
                outputSum := int64(0)
4✔
1587
                for _, txOut := range packet.UnsignedTx.TxOut {
8✔
1588
                        outputSum += txOut.Value
4✔
1589
                }
4✔
1590
                if outputSum <= 0 {
4✔
1591
                        return nil, fmt.Errorf("output sum must be positive")
×
1592
                }
×
1593

1594
                var (
4✔
1595
                        changeIndex int32 = -1
4✔
1596
                        changeType  chanfunding.ChangeAddressType
4✔
1597
                )
4✔
1598
                switch t := coinSelectRequest.ChangeOutput.(type) {
4✔
1599
                // The user wants to use an existing output as change output.
1600
                case *PsbtCoinSelect_ExistingOutputIndex:
4✔
1601
                        if t.ExistingOutputIndex < 0 ||
4✔
1602
                                t.ExistingOutputIndex >= numOutputs {
4✔
1603

×
1604
                                return nil, fmt.Errorf("change output index "+
×
1605
                                        "out of range: %d",
×
1606
                                        t.ExistingOutputIndex)
×
1607
                        }
×
1608

1609
                        changeIndex = t.ExistingOutputIndex
4✔
1610

4✔
1611
                        changeOut := packet.UnsignedTx.TxOut[changeIndex]
4✔
1612
                        _, err := txscript.ParsePkScript(changeOut.PkScript)
4✔
1613
                        if err != nil {
4✔
1614
                                return nil, fmt.Errorf("error parsing change "+
×
1615
                                        "script: %w", err)
×
1616
                        }
×
1617

1618
                        changeType = chanfunding.ExistingChangeAddress
4✔
1619

1620
                // The user wants to use a new output as change output.
1621
                case *PsbtCoinSelect_Add:
×
1622
                        // We already set the change index to -1 above to
×
1623
                        // indicate no change output should be used if possible
×
1624
                        // or a new one should be created if needed. So we only
×
1625
                        // need to parse the type of change output we want to
×
1626
                        // create.
×
1627
                        switch req.ChangeType {
×
1628
                        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
×
1629
                                changeType = chanfunding.P2TRChangeAddress
×
1630

1631
                        default:
×
1632
                                changeType = chanfunding.P2WKHChangeAddress
×
1633
                        }
1634

1635
                default:
×
1636
                        return nil, fmt.Errorf("unknown change output type")
×
1637
                }
1638

1639
                maxFeeRatio := chanfunding.DefaultMaxFeeRatio
4✔
1640

4✔
1641
                if req.MaxFeeRatio != 0 {
4✔
1642
                        maxFeeRatio = req.MaxFeeRatio
×
1643
                }
×
1644

1645
                // Run the actual funding process now, using the channel funding
1646
                // coin selection algorithm.
1647
                return w.fundPsbtCoinSelect(
4✔
1648
                        account, changeIndex, packet, minConfs, changeType,
4✔
1649
                        feeSatPerKW, coinSelectionStrategy, maxFeeRatio,
4✔
1650
                )
4✔
1651

1652
        // The template is specified as a RPC message. We need to create a new
1653
        // PSBT and copy the RPC information over.
1654
        case req.GetRaw() != nil:
4✔
1655
                tpl := req.GetRaw()
4✔
1656

4✔
1657
                txOut := make([]*wire.TxOut, 0, len(tpl.Outputs))
4✔
1658
                for addrStr, amt := range tpl.Outputs {
8✔
1659
                        addr, err := btcutil.DecodeAddress(
4✔
1660
                                addrStr, w.cfg.ChainParams,
4✔
1661
                        )
4✔
1662
                        if err != nil {
4✔
1663
                                return nil, fmt.Errorf("error parsing address "+
×
1664
                                        "%s for network %s: %v", addrStr,
×
1665
                                        w.cfg.ChainParams.Name, err)
×
1666
                        }
×
1667

1668
                        if !addr.IsForNet(w.cfg.ChainParams) {
4✔
1669
                                return nil, fmt.Errorf("address is not for %s",
×
1670
                                        w.cfg.ChainParams.Name)
×
1671
                        }
×
1672

1673
                        pkScript, err := txscript.PayToAddrScript(addr)
4✔
1674
                        if err != nil {
4✔
1675
                                return nil, fmt.Errorf("error getting pk "+
×
1676
                                        "script for address %s: %w", addrStr,
×
1677
                                        err)
×
1678
                        }
×
1679

1680
                        txOut = append(txOut, &wire.TxOut{
4✔
1681
                                Value:    int64(amt),
4✔
1682
                                PkScript: pkScript,
4✔
1683
                        })
4✔
1684
                }
1685

1686
                txIn := make([]*wire.OutPoint, len(tpl.Inputs))
4✔
1687
                for idx, in := range tpl.Inputs {
4✔
1688
                        op, err := UnmarshallOutPoint(in)
×
1689
                        if err != nil {
×
1690
                                return nil, fmt.Errorf("error parsing "+
×
1691
                                        "outpoint: %w", err)
×
1692
                        }
×
1693
                        txIn[idx] = op
×
1694
                }
1695

1696
                sequences := make([]uint32, len(txIn))
4✔
1697
                packet, err := psbt.New(txIn, txOut, 2, 0, sequences)
4✔
1698
                if err != nil {
4✔
1699
                        return nil, fmt.Errorf("could not create PSBT: %w", err)
×
1700
                }
×
1701

1702
                // Run the actual funding process now, using the internal
1703
                // wallet.
1704
                return w.fundPsbtInternalWallet(
4✔
1705
                        account, keyScopeFromChangeAddressType(req.ChangeType),
4✔
1706
                        packet, minConfs, feeSatPerKW, coinSelectionStrategy,
4✔
1707
                )
4✔
1708

1709
        default:
×
1710
                return nil, fmt.Errorf("transaction template missing, need " +
×
1711
                        "to specify either PSBT or raw TX template")
×
1712
        }
1713
}
1714

1715
// fundPsbtInternalWallet uses the "old" PSBT funding method of the internal
1716
// wallet that does not allow specifying custom inputs while selecting coins.
1717
func (w *WalletKit) fundPsbtInternalWallet(account string,
1718
        keyScope *waddrmgr.KeyScope, packet *psbt.Packet, minConfs int32,
1719
        feeSatPerKW chainfee.SatPerKWeight,
1720
        strategy base.CoinSelectionStrategy) (*FundPsbtResponse, error) {
4✔
1721

4✔
1722
        // The RPC parsing part is now over. Several of the following operations
4✔
1723
        // require us to hold the global coin selection lock, so we do the rest
4✔
1724
        // of the tasks while holding the lock. The result is a list of locked
4✔
1725
        // UTXOs.
4✔
1726
        var response *FundPsbtResponse
4✔
1727
        err := w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
8✔
1728
                // In case the user did specify inputs, we need to make sure
4✔
1729
                // they are known to us, still unspent and not yet locked.
4✔
1730
                if len(packet.UnsignedTx.TxIn) > 0 {
8✔
1731
                        // Get a list of all unspent witness outputs.
4✔
1732
                        utxos, err := w.cfg.Wallet.ListUnspentWitness(
4✔
1733
                                minConfs, defaultMaxConf, account,
4✔
1734
                        )
4✔
1735
                        if err != nil {
4✔
1736
                                return err
×
1737
                        }
×
1738

1739
                        // filterFn makes sure utxos which are unconfirmed and
1740
                        // still used by the sweeper are not used.
1741
                        filterFn := func(u *lnwallet.Utxo) bool {
8✔
1742
                                // Confirmed utxos are always allowed.
4✔
1743
                                if u.Confirmations > 0 {
8✔
1744
                                        return true
4✔
1745
                                }
4✔
1746

1747
                                // Unconfirmed utxos in use by the sweeper are
1748
                                // not stable to use because they can be
1749
                                // replaced.
1750
                                if w.cfg.Sweeper.IsSweeperOutpoint(u.OutPoint) {
8✔
1751
                                        log.Warnf("Cannot use unconfirmed "+
4✔
1752
                                                "utxo=%v because it is "+
4✔
1753
                                                "unstable and could be "+
4✔
1754
                                                "replaced", u.OutPoint)
4✔
1755

4✔
1756
                                        return false
4✔
1757
                                }
4✔
1758

1759
                                return true
×
1760
                        }
1761

1762
                        eligibleUtxos := fn.Filter(utxos, filterFn)
4✔
1763

4✔
1764
                        // Validate all inputs against our known list of UTXOs
4✔
1765
                        // now.
4✔
1766
                        err = verifyInputsUnspent(
4✔
1767
                                packet.UnsignedTx.TxIn, eligibleUtxos,
4✔
1768
                        )
4✔
1769
                        if err != nil {
8✔
1770
                                return err
4✔
1771
                        }
4✔
1772
                }
1773

1774
                // currentHeight is needed to determine whether the internal
1775
                // wallet utxo is still unconfirmed.
1776
                _, currentHeight, err := w.cfg.Chain.GetBestBlock()
4✔
1777
                if err != nil {
4✔
1778
                        return fmt.Errorf("unable to retrieve current "+
×
1779
                                "height: %v", err)
×
1780
                }
×
1781

1782
                // restrictUnstableUtxos is a filter function which disallows
1783
                // the usage of unconfirmed outputs published (still in use) by
1784
                // the sweeper.
1785
                restrictUnstableUtxos := func(utxo wtxmgr.Credit) bool {
8✔
1786
                        // Wallet utxos which are unmined have a height
4✔
1787
                        // of -1.
4✔
1788
                        if utxo.Height != -1 && utxo.Height <= currentHeight {
8✔
1789
                                // Confirmed utxos are always allowed.
4✔
1790
                                return true
4✔
1791
                        }
4✔
1792

1793
                        // Utxos used by the sweeper are not used for
1794
                        // channel openings.
1795
                        allowed := !w.cfg.Sweeper.IsSweeperOutpoint(
4✔
1796
                                utxo.OutPoint,
4✔
1797
                        )
4✔
1798
                        if !allowed {
8✔
1799
                                log.Warnf("Cannot use unconfirmed "+
4✔
1800
                                        "utxo=%v because it is "+
4✔
1801
                                        "unstable and could be "+
4✔
1802
                                        "replaced", utxo.OutPoint)
4✔
1803
                        }
4✔
1804

1805
                        return allowed
4✔
1806
                }
1807

1808
                // We made sure the input from the user is as sane as possible.
1809
                // We can now ask the wallet to fund the TX. This will not yet
1810
                // lock any coins but might still change the wallet DB by
1811
                // generating a new change address.
1812
                changeIndex, err := w.cfg.Wallet.FundPsbt(
4✔
1813
                        packet, minConfs, feeSatPerKW, account, keyScope,
4✔
1814
                        strategy, restrictUnstableUtxos,
4✔
1815
                )
4✔
1816
                if err != nil {
8✔
1817
                        return fmt.Errorf("wallet couldn't fund PSBT: %w", err)
4✔
1818
                }
4✔
1819

1820
                // Now we have obtained a set of coins that can be used to fund
1821
                // the TX. Let's lock them to be sure they aren't spent by the
1822
                // time the PSBT is published. This is the action we do here
1823
                // that could cause an error. Therefore, if some of the UTXOs
1824
                // cannot be locked, the rollback of the other's locks also
1825
                // happens in this function. If we ever need to do more after
1826
                // this function, we need to extract the rollback needs to be
1827
                // extracted into a defer.
1828
                outpoints := make([]wire.OutPoint, len(packet.UnsignedTx.TxIn))
4✔
1829
                for i, txIn := range packet.UnsignedTx.TxIn {
8✔
1830
                        outpoints[i] = txIn.PreviousOutPoint
4✔
1831
                }
4✔
1832

1833
                response, err = w.lockAndCreateFundingResponse(
4✔
1834
                        packet, outpoints, changeIndex,
4✔
1835
                )
4✔
1836

4✔
1837
                return err
4✔
1838
        })
1839
        if err != nil {
8✔
1840
                return nil, err
4✔
1841
        }
4✔
1842

1843
        return response, nil
4✔
1844
}
1845

1846
// fundPsbtCoinSelect uses the "new" PSBT funding method using the channel
1847
// funding coin selection algorithm that allows specifying custom inputs while
1848
// selecting coins.
1849
func (w *WalletKit) fundPsbtCoinSelect(account string, changeIndex int32,
1850
        packet *psbt.Packet, minConfs int32,
1851
        changeType chanfunding.ChangeAddressType,
1852
        feeRate chainfee.SatPerKWeight, strategy base.CoinSelectionStrategy,
1853
        maxFeeRatio float64) (*FundPsbtResponse, error) {
4✔
1854

4✔
1855
        // We want to make sure we don't select any inputs that are already
4✔
1856
        // specified in the template. To do that, we require those inputs to
4✔
1857
        // either not belong to this lnd at all or to be already locked through
4✔
1858
        // a manual lock call by the user. Either way, they should not appear in
4✔
1859
        // the list of unspent outputs.
4✔
1860
        err := w.assertNotAvailable(packet.UnsignedTx.TxIn, minConfs, account)
4✔
1861
        if err != nil {
4✔
1862
                return nil, err
×
1863
        }
×
1864

1865
        // In case the user just specified the input outpoints of UTXOs we own,
1866
        // the fee estimation below will error out because the UTXO information
1867
        // is missing. We need to fetch the UTXO information from the wallet
1868
        // and add it to the PSBT. We ignore inputs we don't actually know as
1869
        // they could belong to another wallet.
1870
        err = w.cfg.Wallet.DecorateInputs(packet, false)
4✔
1871
        if err != nil {
4✔
1872
                return nil, fmt.Errorf("error decorating inputs: %w", err)
×
1873
        }
×
1874

1875
        // Before we select anything, we need to calculate the input, output and
1876
        // current weight amounts. While doing that we also ensure the PSBT has
1877
        // all the required information we require at this step.
1878
        var (
4✔
1879
                inputSum, outputSum btcutil.Amount
4✔
1880
                estimator           input.TxWeightEstimator
4✔
1881
        )
4✔
1882
        for i := range packet.Inputs {
8✔
1883
                in := packet.Inputs[i]
4✔
1884

4✔
1885
                err := btcwallet.EstimateInputWeight(&in, &estimator)
4✔
1886
                if err != nil {
4✔
1887
                        return nil, fmt.Errorf("error estimating input "+
×
1888
                                "weight: %w", err)
×
1889
                }
×
1890

1891
                inputSum += btcutil.Amount(in.WitnessUtxo.Value)
4✔
1892
        }
1893
        for i := range packet.UnsignedTx.TxOut {
8✔
1894
                out := packet.UnsignedTx.TxOut[i]
4✔
1895

4✔
1896
                estimator.AddOutput(out.PkScript)
4✔
1897
                outputSum += btcutil.Amount(out.Value)
4✔
1898
        }
4✔
1899

1900
        // The amount we want to fund is the total output sum plus the current
1901
        // fee estimate, minus the sum of any already specified inputs. Since we
1902
        // pass the estimator of the current transaction into the coin selection
1903
        // algorithm, we don't need to subtract the fees here.
1904
        fundingAmount := outputSum - inputSum
4✔
1905

4✔
1906
        var changeDustLimit btcutil.Amount
4✔
1907
        switch changeType {
4✔
1908
        case chanfunding.P2TRChangeAddress:
×
1909
                changeDustLimit = lnwallet.DustLimitForSize(input.P2TRSize)
×
1910

1911
        case chanfunding.P2WKHChangeAddress:
×
1912
                changeDustLimit = lnwallet.DustLimitForSize(input.P2WPKHSize)
×
1913

1914
        case chanfunding.ExistingChangeAddress:
4✔
1915
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
4✔
1916
                changeDustLimit = lnwallet.DustLimitForSize(
4✔
1917
                        len(changeOut.PkScript),
4✔
1918
                )
4✔
1919
        }
1920

1921
        // Do we already have enough inputs specified to pay for the TX as it
1922
        // is? In that case we only need to allocate any change, if there is
1923
        // any.
1924
        packetFeeNoChange := feeRate.FeeForWeight(estimator.Weight())
4✔
1925
        if inputSum >= outputSum+packetFeeNoChange {
4✔
1926
                // Calculate the packet's fee with a change output so, so we can
×
1927
                // let the coin selection algorithm decide whether to use a
×
1928
                // change output or not.
×
1929
                switch changeType {
×
1930
                case chanfunding.P2TRChangeAddress:
×
1931
                        estimator.AddP2TROutput()
×
1932

1933
                case chanfunding.P2WKHChangeAddress:
×
1934
                        estimator.AddP2WKHOutput()
×
1935
                }
1936
                packetFeeWithChange := feeRate.FeeForWeight(estimator.Weight())
×
1937

×
1938
                changeAmt, needMore, err := chanfunding.CalculateChangeAmount(
×
1939
                        inputSum, outputSum, packetFeeNoChange,
×
1940
                        packetFeeWithChange, changeDustLimit, changeType,
×
1941
                        maxFeeRatio,
×
1942
                )
×
1943
                if err != nil {
×
1944
                        return nil, fmt.Errorf("error calculating change "+
×
1945
                                "amount: %w", err)
×
1946
                }
×
1947

1948
                // We shouldn't get into this branch if the input sum isn't
1949
                // enough to pay for the current package without a change
1950
                // output. So this should never be non-zero.
1951
                if needMore != 0 {
×
1952
                        return nil, fmt.Errorf("internal error with change " +
×
1953
                                "amount calculation")
×
1954
                }
×
1955

1956
                if changeAmt > 0 {
×
1957
                        changeIndex, err = w.handleChange(
×
1958
                                packet, changeIndex, int64(changeAmt),
×
1959
                                changeType, account,
×
1960
                        )
×
1961
                        if err != nil {
×
1962
                                return nil, fmt.Errorf("error handling change "+
×
1963
                                        "amount: %w", err)
×
1964
                        }
×
1965
                }
1966

1967
                // We're done. Let's serialize and return the updated package.
1968
                return w.lockAndCreateFundingResponse(packet, nil, changeIndex)
×
1969
        }
1970

1971
        // The RPC parsing part is now over. Several of the following operations
1972
        // require us to hold the global coin selection lock, so we do the rest
1973
        // of the tasks while holding the lock. The result is a list of locked
1974
        // UTXOs.
1975
        var response *FundPsbtResponse
4✔
1976
        err = w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
8✔
1977
                // Get a list of all unspent witness outputs.
4✔
1978
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
4✔
1979
                        minConfs, defaultMaxConf, account,
4✔
1980
                )
4✔
1981
                if err != nil {
4✔
1982
                        return err
×
1983
                }
×
1984

1985
                coins := make([]base.Coin, len(utxos))
4✔
1986
                for i, utxo := range utxos {
8✔
1987
                        coins[i] = base.Coin{
4✔
1988
                                TxOut: wire.TxOut{
4✔
1989
                                        Value:    int64(utxo.Value),
4✔
1990
                                        PkScript: utxo.PkScript,
4✔
1991
                                },
4✔
1992
                                OutPoint: utxo.OutPoint,
4✔
1993
                        }
4✔
1994
                }
4✔
1995

1996
                selectedCoins, changeAmount, err := chanfunding.CoinSelect(
4✔
1997
                        feeRate, fundingAmount, changeDustLimit, coins,
4✔
1998
                        strategy, estimator, changeType, maxFeeRatio,
4✔
1999
                )
4✔
2000
                if err != nil {
4✔
2001
                        return fmt.Errorf("error selecting coins: %w", err)
×
2002
                }
×
2003

2004
                if changeAmount > 0 {
8✔
2005
                        changeIndex, err = w.handleChange(
4✔
2006
                                packet, changeIndex, int64(changeAmount),
4✔
2007
                                changeType, account,
4✔
2008
                        )
4✔
2009
                        if err != nil {
4✔
2010
                                return fmt.Errorf("error handling change "+
×
2011
                                        "amount: %w", err)
×
2012
                        }
×
2013
                }
2014

2015
                addedOutpoints := make([]wire.OutPoint, len(selectedCoins))
4✔
2016
                for i := range selectedCoins {
8✔
2017
                        coin := selectedCoins[i]
4✔
2018
                        addedOutpoints[i] = coin.OutPoint
4✔
2019

4✔
2020
                        packet.UnsignedTx.TxIn = append(
4✔
2021
                                packet.UnsignedTx.TxIn, &wire.TxIn{
4✔
2022
                                        PreviousOutPoint: coin.OutPoint,
4✔
2023
                                },
4✔
2024
                        )
4✔
2025
                        packet.Inputs = append(packet.Inputs, psbt.PInput{
4✔
2026
                                WitnessUtxo: &coin.TxOut,
4✔
2027
                        })
4✔
2028
                }
4✔
2029

2030
                // Now that we've added the bare TX inputs, we also need to add
2031
                // the more verbose input information to the packet, so a future
2032
                // signer doesn't need to do any lookups. We skip any inputs
2033
                // that our wallet doesn't own.
2034
                err = w.cfg.Wallet.DecorateInputs(packet, false)
4✔
2035
                if err != nil {
4✔
2036
                        return fmt.Errorf("error decorating inputs: %w", err)
×
2037
                }
×
2038

2039
                response, err = w.lockAndCreateFundingResponse(
4✔
2040
                        packet, addedOutpoints, changeIndex,
4✔
2041
                )
4✔
2042

4✔
2043
                return err
4✔
2044
        })
2045
        if err != nil {
4✔
2046
                return nil, err
×
2047
        }
×
2048

2049
        return response, nil
4✔
2050
}
2051

2052
// assertNotAvailable makes sure the specified inputs either don't belong to
2053
// this node or are already locked by the user.
2054
func (w *WalletKit) assertNotAvailable(inputs []*wire.TxIn, minConfs int32,
2055
        account string) error {
4✔
2056

4✔
2057
        return w.cfg.CoinSelectionLocker.WithCoinSelectLock(func() error {
8✔
2058
                // Get a list of all unspent witness outputs.
4✔
2059
                utxos, err := w.cfg.Wallet.ListUnspentWitness(
4✔
2060
                        minConfs, defaultMaxConf, account,
4✔
2061
                )
4✔
2062
                if err != nil {
4✔
2063
                        return fmt.Errorf("error fetching UTXOs: %w", err)
×
2064
                }
×
2065

2066
                // We'll now check that none of the inputs specified in the
2067
                // template are available to us. That means they either don't
2068
                // belong to us or are already locked by the user.
2069
                for _, txIn := range inputs {
8✔
2070
                        for _, utxo := range utxos {
8✔
2071
                                if txIn.PreviousOutPoint == utxo.OutPoint {
4✔
2072
                                        return fmt.Errorf("input %v is not "+
×
2073
                                                "locked", txIn.PreviousOutPoint)
×
2074
                                }
×
2075
                        }
2076
                }
2077

2078
                return nil
4✔
2079
        })
2080
}
2081

2082
// lockAndCreateFundingResponse locks the given outpoints and creates a funding
2083
// response with the serialized PSBT, the change index and the locked UTXOs.
2084
func (w *WalletKit) lockAndCreateFundingResponse(packet *psbt.Packet,
2085
        newOutpoints []wire.OutPoint, changeIndex int32) (*FundPsbtResponse,
2086
        error) {
4✔
2087

4✔
2088
        // Make sure we can properly serialize the packet. If this goes wrong
4✔
2089
        // then something isn't right with the inputs, and we probably shouldn't
4✔
2090
        // try to lock any of them.
4✔
2091
        var buf bytes.Buffer
4✔
2092
        err := packet.Serialize(&buf)
4✔
2093
        if err != nil {
4✔
2094
                return nil, fmt.Errorf("error serializing funded PSBT: %w", err)
×
2095
        }
×
2096

2097
        locks, err := lockInputs(w.cfg.Wallet, newOutpoints)
4✔
2098
        if err != nil {
4✔
2099
                return nil, fmt.Errorf("could not lock inputs: %w", err)
×
2100
        }
×
2101

2102
        // Convert the lock leases to the RPC format.
2103
        rpcLocks := marshallLeases(locks)
4✔
2104

4✔
2105
        return &FundPsbtResponse{
4✔
2106
                FundedPsbt:        buf.Bytes(),
4✔
2107
                ChangeOutputIndex: changeIndex,
4✔
2108
                LockedUtxos:       rpcLocks,
4✔
2109
        }, nil
4✔
2110
}
2111

2112
// handleChange is a closure that either adds the non-zero change amount to an
2113
// existing output or creates a change output. The function returns the new
2114
// change output index if a new change output was added.
2115
func (w *WalletKit) handleChange(packet *psbt.Packet, changeIndex int32,
2116
        changeAmount int64, changeType chanfunding.ChangeAddressType,
2117
        changeAccount string) (int32, error) {
4✔
2118

4✔
2119
        // Does an existing output get the change?
4✔
2120
        if changeIndex >= 0 {
8✔
2121
                changeOut := packet.UnsignedTx.TxOut[changeIndex]
4✔
2122
                changeOut.Value += changeAmount
4✔
2123

4✔
2124
                return changeIndex, nil
4✔
2125
        }
4✔
2126

2127
        // The user requested a new change output.
2128
        addrType := addrTypeFromChangeAddressType(changeType)
×
2129
        changeAddr, err := w.cfg.Wallet.NewAddress(
×
2130
                addrType, true, changeAccount,
×
2131
        )
×
2132
        if err != nil {
×
2133
                return 0, fmt.Errorf("could not derive change address: %w", err)
×
2134
        }
×
2135

2136
        changeScript, err := txscript.PayToAddrScript(changeAddr)
×
2137
        if err != nil {
×
2138
                return 0, fmt.Errorf("could not derive change script: %w", err)
×
2139
        }
×
2140

2141
        // We need to add the derivation info for the change address in case it
2142
        // is a P2TR address. This is mostly to prove it's a bare BIP-0086
2143
        // address, which is required for some protocols (such as Taproot
2144
        // Assets).
2145
        pOut := psbt.POutput{}
×
2146
        _, isTaprootChangeAddr := changeAddr.(*btcutil.AddressTaproot)
×
2147
        if isTaprootChangeAddr {
×
2148
                changeAddrInfo, err := w.cfg.Wallet.AddressInfo(changeAddr)
×
2149
                if err != nil {
×
2150
                        return 0, fmt.Errorf("could not get address info: %w",
×
2151
                                err)
×
2152
                }
×
2153

2154
                deriv, trDeriv, _, err := btcwallet.Bip32DerivationFromAddress(
×
2155
                        changeAddrInfo,
×
2156
                )
×
2157
                if err != nil {
×
2158
                        return 0, fmt.Errorf("could not get derivation info: "+
×
2159
                                "%w", err)
×
2160
                }
×
2161

2162
                pOut.TaprootInternalKey = trDeriv.XOnlyPubKey
×
2163
                pOut.Bip32Derivation = []*psbt.Bip32Derivation{deriv}
×
2164
                pOut.TaprootBip32Derivation = []*psbt.TaprootBip32Derivation{
×
2165
                        trDeriv,
×
2166
                }
×
2167
        }
2168

2169
        newChangeIndex := int32(len(packet.Outputs))
×
2170
        packet.UnsignedTx.TxOut = append(
×
2171
                packet.UnsignedTx.TxOut, &wire.TxOut{
×
2172
                        Value:    changeAmount,
×
2173
                        PkScript: changeScript,
×
2174
                },
×
2175
        )
×
2176
        packet.Outputs = append(packet.Outputs, pOut)
×
2177

×
2178
        return newChangeIndex, nil
×
2179
}
2180

2181
// marshallLeases converts the lock leases to the RPC format.
2182
func marshallLeases(locks []*base.ListLeasedOutputResult) []*UtxoLease {
4✔
2183
        rpcLocks := make([]*UtxoLease, len(locks))
4✔
2184
        for idx, lock := range locks {
8✔
2185
                lock := lock
4✔
2186

4✔
2187
                rpcLocks[idx] = &UtxoLease{
4✔
2188
                        Id:         lock.LockID[:],
4✔
2189
                        Outpoint:   lnrpc.MarshalOutPoint(&lock.Outpoint),
4✔
2190
                        Expiration: uint64(lock.Expiration.Unix()),
4✔
2191
                        PkScript:   lock.PkScript,
4✔
2192
                        Value:      uint64(lock.Value),
4✔
2193
                }
4✔
2194
        }
4✔
2195

2196
        return rpcLocks
4✔
2197
}
2198

2199
// keyScopeFromChangeAddressType maps a ChangeAddressType from protobuf to a
2200
// KeyScope. If the type is ChangeAddressType_CHANGE_ADDRESS_TYPE_UNSPECIFIED,
2201
// it returns nil.
2202
func keyScopeFromChangeAddressType(
2203
        changeAddressType ChangeAddressType) *waddrmgr.KeyScope {
4✔
2204

4✔
2205
        switch changeAddressType {
4✔
2206
        case ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR:
4✔
2207
                return &waddrmgr.KeyScopeBIP0086
4✔
2208

2209
        default:
4✔
2210
                return nil
4✔
2211
        }
2212
}
2213

2214
// addrTypeFromChangeAddressType maps a chanfunding.ChangeAddressType to the
2215
// lnwallet.AddressType.
2216
func addrTypeFromChangeAddressType(
2217
        changeAddressType chanfunding.ChangeAddressType) lnwallet.AddressType {
×
2218

×
2219
        switch changeAddressType {
×
2220
        case chanfunding.P2TRChangeAddress:
×
2221
                return lnwallet.TaprootPubkey
×
2222

2223
        default:
×
2224
                return lnwallet.WitnessPubKey
×
2225
        }
2226
}
2227

2228
// SignPsbt expects a partial transaction with all inputs and outputs fully
2229
// declared and tries to sign all unsigned inputs that have all required fields
2230
// (UTXO information, BIP32 derivation information, witness or sig scripts)
2231
// set.
2232
// If no error is returned, the PSBT is ready to be given to the next signer or
2233
// to be finalized if lnd was the last signer.
2234
//
2235
// NOTE: This RPC only signs inputs (and only those it can sign), it does not
2236
// perform any other tasks (such as coin selection, UTXO locking or
2237
// input/output/fee value validation, PSBT finalization). Any input that is
2238
// incomplete will be skipped.
2239
func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) (
2240
        *SignPsbtResponse, error) {
4✔
2241

4✔
2242
        packet, err := psbt.NewFromRawBytes(
4✔
2243
                bytes.NewReader(req.FundedPsbt), false,
4✔
2244
        )
4✔
2245
        if err != nil {
4✔
2246
                log.Debugf("Error parsing PSBT: %v, raw input: %x", err,
×
2247
                        req.FundedPsbt)
×
2248
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
2249
        }
×
2250

2251
        // Before we attempt to sign the packet, ensure that every input either
2252
        // has a witness UTXO, or a non witness UTXO.
2253
        for idx := range packet.UnsignedTx.TxIn {
8✔
2254
                in := packet.Inputs[idx]
4✔
2255

4✔
2256
                // Doesn't have either a witness or non witness UTXO so we need
4✔
2257
                // to exit here as otherwise signing will fail.
4✔
2258
                if in.WitnessUtxo == nil && in.NonWitnessUtxo == nil {
8✔
2259
                        return nil, fmt.Errorf("input (index=%v) doesn't "+
4✔
2260
                                "specify any UTXO info", idx)
4✔
2261
                }
4✔
2262
        }
2263

2264
        // Let the wallet do the heavy lifting. This will sign all inputs that
2265
        // we have the UTXO for. If some inputs can't be signed and don't have
2266
        // witness data attached, they will just be skipped.
2267
        signedInputs, err := w.cfg.Wallet.SignPsbt(packet)
4✔
2268
        if err != nil {
4✔
2269
                return nil, fmt.Errorf("error signing PSBT: %w", err)
×
2270
        }
×
2271

2272
        // Serialize the signed PSBT in both the packet and wire format.
2273
        var signedPsbtBytes bytes.Buffer
4✔
2274
        err = packet.Serialize(&signedPsbtBytes)
4✔
2275
        if err != nil {
4✔
2276
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
2277
        }
×
2278

2279
        return &SignPsbtResponse{
4✔
2280
                SignedPsbt:   signedPsbtBytes.Bytes(),
4✔
2281
                SignedInputs: signedInputs,
4✔
2282
        }, nil
4✔
2283
}
2284

2285
// FinalizePsbt expects a partial transaction with all inputs and outputs fully
2286
// declared and tries to sign all inputs that belong to the wallet. Lnd must be
2287
// the last signer of the transaction. That means, if there are any unsigned
2288
// non-witness inputs or inputs without UTXO information attached or inputs
2289
// without witness data that do not belong to lnd's wallet, this method will
2290
// fail. If no error is returned, the PSBT is ready to be extracted and the
2291
// final TX within to be broadcast.
2292
//
2293
// NOTE: This method does NOT publish the transaction once finalized. It is the
2294
// caller's responsibility to either publish the transaction on success or
2295
// unlock/release any locked UTXOs in case of an error in this method.
2296
func (w *WalletKit) FinalizePsbt(_ context.Context,
2297
        req *FinalizePsbtRequest) (*FinalizePsbtResponse, error) {
4✔
2298

4✔
2299
        // We'll assume the PSBT was funded by the default account unless
4✔
2300
        // otherwise specified.
4✔
2301
        account := lnwallet.DefaultAccountName
4✔
2302
        if req.Account != "" {
4✔
2303
                account = req.Account
×
2304
        }
×
2305

2306
        // Parse the funded PSBT.
2307
        packet, err := psbt.NewFromRawBytes(
4✔
2308
                bytes.NewReader(req.FundedPsbt), false,
4✔
2309
        )
4✔
2310
        if err != nil {
4✔
2311
                return nil, fmt.Errorf("error parsing PSBT: %w", err)
×
2312
        }
×
2313

2314
        // The only check done at this level is to validate that the PSBT is
2315
        // not complete. The wallet performs all other checks.
2316
        if packet.IsComplete() {
4✔
2317
                return nil, fmt.Errorf("PSBT is already fully signed")
×
2318
        }
×
2319

2320
        // Let the wallet do the heavy lifting. This will sign all inputs that
2321
        // we have the UTXO for. If some inputs can't be signed and don't have
2322
        // witness data attached, this will fail.
2323
        err = w.cfg.Wallet.FinalizePsbt(packet, account)
4✔
2324
        if err != nil {
4✔
2325
                return nil, fmt.Errorf("error finalizing PSBT: %w", err)
×
2326
        }
×
2327

2328
        var (
4✔
2329
                finalPsbtBytes bytes.Buffer
4✔
2330
                finalTxBytes   bytes.Buffer
4✔
2331
        )
4✔
2332

4✔
2333
        // Serialize the finalized PSBT in both the packet and wire format.
4✔
2334
        err = packet.Serialize(&finalPsbtBytes)
4✔
2335
        if err != nil {
4✔
2336
                return nil, fmt.Errorf("error serializing PSBT: %w", err)
×
2337
        }
×
2338
        finalTx, err := psbt.Extract(packet)
4✔
2339
        if err != nil {
4✔
2340
                return nil, fmt.Errorf("unable to extract final TX: %w", err)
×
2341
        }
×
2342
        err = finalTx.Serialize(&finalTxBytes)
4✔
2343
        if err != nil {
4✔
2344
                return nil, fmt.Errorf("error serializing final TX: %w", err)
×
2345
        }
×
2346

2347
        return &FinalizePsbtResponse{
4✔
2348
                SignedPsbt: finalPsbtBytes.Bytes(),
4✔
2349
                RawFinalTx: finalTxBytes.Bytes(),
4✔
2350
        }, nil
4✔
2351
}
2352

2353
// marshalWalletAccount converts the properties of an account into its RPC
2354
// representation.
2355
func marshalWalletAccount(internalScope waddrmgr.KeyScope,
2356
        account *waddrmgr.AccountProperties) (*Account, error) {
4✔
2357

4✔
2358
        var addrType AddressType
4✔
2359
        switch account.KeyScope {
4✔
2360
        case waddrmgr.KeyScopeBIP0049Plus:
4✔
2361
                // No address schema present represents the traditional BIP-0049
4✔
2362
                // address derivation scheme.
4✔
2363
                if account.AddrSchema == nil {
8✔
2364
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
4✔
2365
                        break
4✔
2366
                }
2367

2368
                switch *account.AddrSchema {
4✔
2369
                case waddrmgr.KeyScopeBIP0049AddrSchema:
4✔
2370
                        addrType = AddressType_NESTED_WITNESS_PUBKEY_HASH
4✔
2371

2372
                case waddrmgr.ScopeAddrMap[waddrmgr.KeyScopeBIP0049Plus]:
4✔
2373
                        addrType = AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH
4✔
2374

2375
                default:
×
2376
                        return nil, fmt.Errorf("unsupported address schema %v",
×
2377
                                *account.AddrSchema)
×
2378
                }
2379

2380
        case waddrmgr.KeyScopeBIP0084:
4✔
2381
                addrType = AddressType_WITNESS_PUBKEY_HASH
4✔
2382

2383
        case waddrmgr.KeyScopeBIP0086:
4✔
2384
                addrType = AddressType_TAPROOT_PUBKEY
4✔
2385

2386
        case internalScope:
4✔
2387
                addrType = AddressType_WITNESS_PUBKEY_HASH
4✔
2388

2389
        default:
×
2390
                return nil, fmt.Errorf("account %v has unsupported "+
×
2391
                        "key scope %v", account.AccountName, account.KeyScope)
×
2392
        }
2393

2394
        rpcAccount := &Account{
4✔
2395
                Name:             account.AccountName,
4✔
2396
                AddressType:      addrType,
4✔
2397
                ExternalKeyCount: account.ExternalKeyCount,
4✔
2398
                InternalKeyCount: account.InternalKeyCount,
4✔
2399
                WatchOnly:        account.IsWatchOnly,
4✔
2400
        }
4✔
2401

4✔
2402
        // The remaining fields can only be done on accounts other than the
4✔
2403
        // default imported one existing within each key scope.
4✔
2404
        if account.AccountName != waddrmgr.ImportedAddrAccountName {
8✔
2405
                nonHardenedIndex := account.AccountPubKey.ChildIndex() -
4✔
2406
                        hdkeychain.HardenedKeyStart
4✔
2407
                rpcAccount.ExtendedPublicKey = account.AccountPubKey.String()
4✔
2408
                if account.MasterKeyFingerprint != 0 {
4✔
2409
                        var mkfp [4]byte
×
2410
                        binary.BigEndian.PutUint32(
×
2411
                                mkfp[:], account.MasterKeyFingerprint,
×
2412
                        )
×
2413
                        rpcAccount.MasterKeyFingerprint = mkfp[:]
×
2414
                }
×
2415
                rpcAccount.DerivationPath = fmt.Sprintf("%v/%v'",
4✔
2416
                        account.KeyScope, nonHardenedIndex)
4✔
2417
        }
2418

2419
        return rpcAccount, nil
4✔
2420
}
2421

2422
// marshalWalletAddressList converts the list of address into its RPC
2423
// representation.
2424
func marshalWalletAddressList(w *WalletKit, account *waddrmgr.AccountProperties,
2425
        addressList []lnwallet.AddressProperty) (*AccountWithAddresses, error) {
4✔
2426

4✔
2427
        // Get the RPC representation of account.
4✔
2428
        rpcAccount, err := marshalWalletAccount(
4✔
2429
                w.internalScope(), account,
4✔
2430
        )
4✔
2431
        if err != nil {
4✔
2432
                return nil, err
×
2433
        }
×
2434

2435
        addresses := make([]*AddressProperty, len(addressList))
4✔
2436
        for idx, addr := range addressList {
8✔
2437
                var pubKeyBytes []byte
4✔
2438
                if addr.PublicKey != nil {
8✔
2439
                        pubKeyBytes = addr.PublicKey.SerializeCompressed()
4✔
2440
                }
4✔
2441
                addresses[idx] = &AddressProperty{
4✔
2442
                        Address:        addr.Address,
4✔
2443
                        IsInternal:     addr.Internal,
4✔
2444
                        Balance:        int64(addr.Balance),
4✔
2445
                        DerivationPath: addr.DerivationPath,
4✔
2446
                        PublicKey:      pubKeyBytes,
4✔
2447
                }
4✔
2448
        }
2449

2450
        rpcAddressList := &AccountWithAddresses{
4✔
2451
                Name:           rpcAccount.Name,
4✔
2452
                AddressType:    rpcAccount.AddressType,
4✔
2453
                DerivationPath: rpcAccount.DerivationPath,
4✔
2454
                Addresses:      addresses,
4✔
2455
        }
4✔
2456

4✔
2457
        return rpcAddressList, nil
4✔
2458
}
2459

2460
// ListAccounts retrieves all accounts belonging to the wallet by default. A
2461
// name and key scope filter can be provided to filter through all of the wallet
2462
// accounts and return only those matching.
2463
func (w *WalletKit) ListAccounts(ctx context.Context,
2464
        req *ListAccountsRequest) (*ListAccountsResponse, error) {
4✔
2465

4✔
2466
        // Map the supported address types into their corresponding key scope.
4✔
2467
        var keyScopeFilter *waddrmgr.KeyScope
4✔
2468
        switch req.AddressType {
4✔
2469
        case AddressType_UNKNOWN:
4✔
2470
                break
4✔
2471

2472
        case AddressType_WITNESS_PUBKEY_HASH:
4✔
2473
                keyScope := waddrmgr.KeyScopeBIP0084
4✔
2474
                keyScopeFilter = &keyScope
4✔
2475

2476
        case AddressType_NESTED_WITNESS_PUBKEY_HASH,
2477
                AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
4✔
2478

4✔
2479
                keyScope := waddrmgr.KeyScopeBIP0049Plus
4✔
2480
                keyScopeFilter = &keyScope
4✔
2481

2482
        case AddressType_TAPROOT_PUBKEY:
4✔
2483
                keyScope := waddrmgr.KeyScopeBIP0086
4✔
2484
                keyScopeFilter = &keyScope
4✔
2485

2486
        default:
×
2487
                return nil, fmt.Errorf("unhandled address type %v",
×
2488
                        req.AddressType)
×
2489
        }
2490

2491
        accounts, err := w.cfg.Wallet.ListAccounts(req.Name, keyScopeFilter)
4✔
2492
        if err != nil {
4✔
2493
                return nil, err
×
2494
        }
×
2495

2496
        rpcAccounts := make([]*Account, 0, len(accounts))
4✔
2497
        for _, account := range accounts {
8✔
2498
                // Don't include the default imported accounts created by the
4✔
2499
                // wallet in the response if they don't have any keys imported.
4✔
2500
                if account.AccountName == waddrmgr.ImportedAddrAccountName &&
4✔
2501
                        account.ImportedKeyCount == 0 {
8✔
2502

4✔
2503
                        continue
4✔
2504
                }
2505

2506
                rpcAccount, err := marshalWalletAccount(
4✔
2507
                        w.internalScope(), account,
4✔
2508
                )
4✔
2509
                if err != nil {
4✔
2510
                        return nil, err
×
2511
                }
×
2512
                rpcAccounts = append(rpcAccounts, rpcAccount)
4✔
2513
        }
2514

2515
        return &ListAccountsResponse{Accounts: rpcAccounts}, nil
4✔
2516
}
2517

2518
// RequiredReserve returns the minimum amount of satoshis that should be
2519
// kept in the wallet in order to fee bump anchor channels if necessary.
2520
// The value scales with the number of public anchor channels but is
2521
// capped at a maximum.
2522
func (w *WalletKit) RequiredReserve(ctx context.Context,
2523
        req *RequiredReserveRequest) (*RequiredReserveResponse, error) {
4✔
2524

4✔
2525
        numAnchorChans, err := w.cfg.CurrentNumAnchorChans()
4✔
2526
        if err != nil {
4✔
2527
                return nil, err
×
2528
        }
×
2529

2530
        additionalChans := req.AdditionalPublicChannels
4✔
2531
        totalChans := uint32(numAnchorChans) + additionalChans
4✔
2532
        reserved := w.cfg.Wallet.RequiredReserve(totalChans)
4✔
2533

4✔
2534
        return &RequiredReserveResponse{
4✔
2535
                RequiredReserve: int64(reserved),
4✔
2536
        }, nil
4✔
2537
}
2538

2539
// ListAddresses retrieves all the addresses along with their balance. An
2540
// account name filter can be provided to filter through all of the
2541
// wallet accounts and return the addresses of only those matching.
2542
func (w *WalletKit) ListAddresses(ctx context.Context,
2543
        req *ListAddressesRequest) (*ListAddressesResponse, error) {
4✔
2544

4✔
2545
        addressLists, err := w.cfg.Wallet.ListAddresses(
4✔
2546
                req.AccountName,
4✔
2547
                req.ShowCustomAccounts,
4✔
2548
        )
4✔
2549
        if err != nil {
4✔
2550
                return nil, err
×
2551
        }
×
2552

2553
        // Create a slice of accounts from addressLists map.
2554
        accounts := make([]*waddrmgr.AccountProperties, 0, len(addressLists))
4✔
2555
        for account := range addressLists {
8✔
2556
                accounts = append(accounts, account)
4✔
2557
        }
4✔
2558

2559
        // Sort the accounts by derivation path.
2560
        sort.Slice(accounts, func(i, j int) bool {
8✔
2561
                scopeI := accounts[i].KeyScope
4✔
2562
                scopeJ := accounts[j].KeyScope
4✔
2563
                if scopeI.Purpose == scopeJ.Purpose {
4✔
2564
                        if scopeI.Coin == scopeJ.Coin {
×
2565
                                acntNumI := accounts[i].AccountNumber
×
2566
                                acntNumJ := accounts[j].AccountNumber
×
2567
                                return acntNumI < acntNumJ
×
2568
                        }
×
2569

2570
                        return scopeI.Coin < scopeJ.Coin
×
2571
                }
2572

2573
                return scopeI.Purpose < scopeJ.Purpose
4✔
2574
        })
2575

2576
        rpcAddressLists := make([]*AccountWithAddresses, 0, len(addressLists))
4✔
2577
        for _, account := range accounts {
8✔
2578
                addressList := addressLists[account]
4✔
2579
                rpcAddressList, err := marshalWalletAddressList(
4✔
2580
                        w, account, addressList,
4✔
2581
                )
4✔
2582
                if err != nil {
4✔
2583
                        return nil, err
×
2584
                }
×
2585

2586
                rpcAddressLists = append(rpcAddressLists, rpcAddressList)
4✔
2587
        }
2588

2589
        return &ListAddressesResponse{
4✔
2590
                AccountWithAddresses: rpcAddressLists,
4✔
2591
        }, nil
4✔
2592
}
2593

2594
// parseAddrType parses an address type from its RPC representation to a
2595
// *waddrmgr.AddressType.
2596
func parseAddrType(addrType AddressType,
2597
        required bool) (*waddrmgr.AddressType, error) {
4✔
2598

4✔
2599
        switch addrType {
4✔
2600
        case AddressType_UNKNOWN:
×
2601
                if required {
×
2602
                        return nil, fmt.Errorf("an address type must be " +
×
2603
                                "specified")
×
2604
                }
×
2605
                return nil, nil
×
2606

2607
        case AddressType_WITNESS_PUBKEY_HASH:
4✔
2608
                addrTyp := waddrmgr.WitnessPubKey
4✔
2609
                return &addrTyp, nil
4✔
2610

2611
        case AddressType_NESTED_WITNESS_PUBKEY_HASH:
4✔
2612
                addrTyp := waddrmgr.NestedWitnessPubKey
4✔
2613
                return &addrTyp, nil
4✔
2614

2615
        case AddressType_HYBRID_NESTED_WITNESS_PUBKEY_HASH:
4✔
2616
                addrTyp := waddrmgr.WitnessPubKey
4✔
2617
                return &addrTyp, nil
4✔
2618

2619
        case AddressType_TAPROOT_PUBKEY:
4✔
2620
                addrTyp := waddrmgr.TaprootPubKey
4✔
2621
                return &addrTyp, nil
4✔
2622

2623
        default:
×
2624
                return nil, fmt.Errorf("unhandled address type %v", addrType)
×
2625
        }
2626
}
2627

2628
// msgSignaturePrefix is a prefix used to prevent inadvertently signing a
2629
// transaction or a signature. It is prepended in front of the message and
2630
// follows the same standard as bitcoin core and btcd.
2631
const msgSignaturePrefix = "Bitcoin Signed Message:\n"
2632

2633
// SignMessageWithAddr signs a message with the private key of the provided
2634
// address. The address needs to belong to the lnd wallet.
2635
func (w *WalletKit) SignMessageWithAddr(_ context.Context,
2636
        req *SignMessageWithAddrRequest) (*SignMessageWithAddrResponse, error) {
4✔
2637

4✔
2638
        addr, err := btcutil.DecodeAddress(req.Addr, w.cfg.ChainParams)
4✔
2639
        if err != nil {
4✔
2640
                return nil, fmt.Errorf("unable to decode address: %w", err)
×
2641
        }
×
2642

2643
        if !addr.IsForNet(w.cfg.ChainParams) {
4✔
2644
                return nil, fmt.Errorf("encoded address is for "+
×
2645
                        "the wrong network %s", req.Addr)
×
2646
        }
×
2647

2648
        // Fetch address infos from own wallet and check whether it belongs
2649
        // to the lnd wallet.
2650
        managedAddr, err := w.cfg.Wallet.AddressInfo(addr)
4✔
2651
        if err != nil {
4✔
2652
                return nil, fmt.Errorf("address could not be found in the "+
×
2653
                        "wallet database: %w", err)
×
2654
        }
×
2655

2656
        // Verifying by checking the interface type that the wallet knows about
2657
        // the public and private keys so it can sign the message with the
2658
        // private key of this address.
2659
        pubKey, ok := managedAddr.(waddrmgr.ManagedPubKeyAddress)
4✔
2660
        if !ok {
4✔
2661
                return nil, fmt.Errorf("private key to address is unknown")
×
2662
        }
×
2663

2664
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
4✔
2665
        if err != nil {
4✔
2666
                return nil, err
×
2667
        }
×
2668

2669
        // For all address types (P2WKH, NP2WKH,P2TR) the ECDSA compact signing
2670
        // algorithm is used. For P2TR addresses this represents a special case.
2671
        // ECDSA is used to create a compact signature which makes the public
2672
        // key of the signature recoverable. For Schnorr no known compact
2673
        // signing algorithm exists yet.
2674
        privKey, err := pubKey.PrivKey()
4✔
2675
        if err != nil {
4✔
2676
                return nil, fmt.Errorf("no private key could be "+
×
2677
                        "fetched from wallet database: %w", err)
×
2678
        }
×
2679

2680
        sigBytes := ecdsa.SignCompact(privKey, digest, pubKey.Compressed())
4✔
2681

4✔
2682
        // Bitcoin signatures are base64 encoded (being compatible with
4✔
2683
        // bitcoin-core and btcd).
4✔
2684
        sig := base64.StdEncoding.EncodeToString(sigBytes)
4✔
2685

4✔
2686
        return &SignMessageWithAddrResponse{
4✔
2687
                Signature: sig,
4✔
2688
        }, nil
4✔
2689
}
2690

2691
// VerifyMessageWithAddr verifies a signature on a message with a provided
2692
// address, it checks both the validity of the signature itself and then
2693
// verifies whether the signature corresponds to the public key of the
2694
// provided address. There is no dependence on the private key of the address
2695
// therefore also external addresses are allowed to verify signatures.
2696
// Supported address types are P2PKH, P2WKH, NP2WKH, P2TR.
2697
func (w *WalletKit) VerifyMessageWithAddr(_ context.Context,
2698
        req *VerifyMessageWithAddrRequest) (*VerifyMessageWithAddrResponse,
2699
        error) {
4✔
2700

4✔
2701
        sig, err := base64.StdEncoding.DecodeString(req.Signature)
4✔
2702
        if err != nil {
4✔
2703
                return nil, fmt.Errorf("malformed base64 encoding of "+
×
2704
                        "the signature: %w", err)
×
2705
        }
×
2706

2707
        digest, err := doubleHashMessage(msgSignaturePrefix, string(req.Msg))
4✔
2708
        if err != nil {
4✔
2709
                return nil, err
×
2710
        }
×
2711

2712
        pk, wasCompressed, err := ecdsa.RecoverCompact(sig, digest)
4✔
2713
        if err != nil {
4✔
2714
                return nil, fmt.Errorf("unable to recover public key "+
×
2715
                        "from compact signature: %w", err)
×
2716
        }
×
2717

2718
        var serializedPubkey []byte
4✔
2719
        if wasCompressed {
8✔
2720
                serializedPubkey = pk.SerializeCompressed()
4✔
2721
        } else {
4✔
2722
                serializedPubkey = pk.SerializeUncompressed()
×
2723
        }
×
2724

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

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

2735
        var (
4✔
2736
                address    btcutil.Address
4✔
2737
                pubKeyHash = btcutil.Hash160(serializedPubkey)
4✔
2738
        )
4✔
2739

4✔
2740
        // Ensure the address is one of the supported types.
4✔
2741
        switch addr.(type) {
4✔
2742
        case *btcutil.AddressPubKeyHash:
4✔
2743
                address, err = btcutil.NewAddressPubKeyHash(
4✔
2744
                        pubKeyHash, w.cfg.ChainParams,
4✔
2745
                )
4✔
2746
                if err != nil {
4✔
2747
                        return nil, err
×
2748
                }
×
2749

2750
        case *btcutil.AddressWitnessPubKeyHash:
4✔
2751
                address, err = btcutil.NewAddressWitnessPubKeyHash(
4✔
2752
                        pubKeyHash, w.cfg.ChainParams,
4✔
2753
                )
4✔
2754
                if err != nil {
4✔
2755
                        return nil, err
×
2756
                }
×
2757

2758
        case *btcutil.AddressScriptHash:
4✔
2759
                // Check if address is a Nested P2WKH (NP2WKH).
4✔
2760
                address, err = btcutil.NewAddressWitnessPubKeyHash(
4✔
2761
                        pubKeyHash, w.cfg.ChainParams,
4✔
2762
                )
4✔
2763
                if err != nil {
4✔
2764
                        return nil, err
×
2765
                }
×
2766

2767
                witnessScript, err := txscript.PayToAddrScript(address)
4✔
2768
                if err != nil {
4✔
2769
                        return nil, err
×
2770
                }
×
2771

2772
                address, err = btcutil.NewAddressScriptHashFromHash(
4✔
2773
                        btcutil.Hash160(witnessScript), w.cfg.ChainParams,
4✔
2774
                )
4✔
2775
                if err != nil {
4✔
2776
                        return nil, err
×
2777
                }
×
2778

2779
        case *btcutil.AddressTaproot:
4✔
2780
                // Only addresses without a tapscript are allowed because
4✔
2781
                // the verification is using the internal key.
4✔
2782
                tapKey := txscript.ComputeTaprootKeyNoScript(pk)
4✔
2783
                address, err = btcutil.NewAddressTaproot(
4✔
2784
                        schnorr.SerializePubKey(tapKey),
4✔
2785
                        w.cfg.ChainParams,
4✔
2786
                )
4✔
2787
                if err != nil {
4✔
2788
                        return nil, err
×
2789
                }
×
2790

2791
        default:
×
2792
                return nil, fmt.Errorf("unsupported address type")
×
2793
        }
2794

2795
        return &VerifyMessageWithAddrResponse{
4✔
2796
                Valid:  req.Addr == address.EncodeAddress(),
4✔
2797
                Pubkey: serializedPubkey,
4✔
2798
        }, nil
4✔
2799
}
2800

2801
// ImportAccount imports an account backed by an account extended public key.
2802
// The master key fingerprint denotes the fingerprint of the root key
2803
// corresponding to the account public key (also known as the key with
2804
// derivation path m/). This may be required by some hardware wallets for proper
2805
// identification and signing.
2806
//
2807
// The address type can usually be inferred from the key's version, but may be
2808
// required for certain keys to map them into the proper scope.
2809
//
2810
// For BIP-0044 keys, an address type must be specified as we intend to not
2811
// support importing BIP-0044 keys into the wallet using the legacy
2812
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force
2813
// the standard BIP-0049 derivation scheme, while a witness address type will
2814
// force the standard BIP-0084 derivation scheme.
2815
//
2816
// For BIP-0049 keys, an address type must also be specified to make a
2817
// distinction between the standard BIP-0049 address schema (nested witness
2818
// pubkeys everywhere) and our own BIP-0049Plus address schema (nested pubkeys
2819
// externally, witness pubkeys internally).
2820
func (w *WalletKit) ImportAccount(_ context.Context,
2821
        req *ImportAccountRequest) (*ImportAccountResponse, error) {
4✔
2822

4✔
2823
        accountPubKey, err := hdkeychain.NewKeyFromString(req.ExtendedPublicKey)
4✔
2824
        if err != nil {
4✔
2825
                return nil, err
×
2826
        }
×
2827

2828
        var mkfp uint32
4✔
2829
        switch len(req.MasterKeyFingerprint) {
4✔
2830
        // No master key fingerprint provided, which is fine as it's not
2831
        // required.
2832
        case 0:
4✔
2833
        // Expected length.
2834
        case 4:
×
2835
                mkfp = binary.BigEndian.Uint32(req.MasterKeyFingerprint)
×
2836
        default:
×
2837
                return nil, errors.New("invalid length for master key " +
×
2838
                        "fingerprint, expected 4 bytes in big-endian")
×
2839
        }
2840

2841
        addrType, err := parseAddrType(req.AddressType, false)
4✔
2842
        if err != nil {
4✔
2843
                return nil, err
×
2844
        }
×
2845

2846
        accountProps, extAddrs, intAddrs, err := w.cfg.Wallet.ImportAccount(
4✔
2847
                req.Name, accountPubKey, mkfp, addrType, req.DryRun,
4✔
2848
        )
4✔
2849
        if err != nil {
8✔
2850
                return nil, err
4✔
2851
        }
4✔
2852

2853
        rpcAccount, err := marshalWalletAccount(w.internalScope(), accountProps)
4✔
2854
        if err != nil {
4✔
2855
                return nil, err
×
2856
        }
×
2857

2858
        resp := &ImportAccountResponse{Account: rpcAccount}
4✔
2859
        if !req.DryRun {
8✔
2860
                return resp, nil
4✔
2861
        }
4✔
2862

2863
        resp.DryRunExternalAddrs = make([]string, len(extAddrs))
×
2864
        for i := 0; i < len(extAddrs); i++ {
×
2865
                resp.DryRunExternalAddrs[i] = extAddrs[i].String()
×
2866
        }
×
2867
        resp.DryRunInternalAddrs = make([]string, len(intAddrs))
×
2868
        for i := 0; i < len(intAddrs); i++ {
×
2869
                resp.DryRunInternalAddrs[i] = intAddrs[i].String()
×
2870
        }
×
2871

2872
        return resp, nil
×
2873
}
2874

2875
// ImportPublicKey imports a single derived public key into the wallet. The
2876
// address type can usually be inferred from the key's version, but in the case
2877
// of legacy versions (xpub, tpub), an address type must be specified as we
2878
// intend to not support importing BIP-44 keys into the wallet using the legacy
2879
// pay-to-pubkey-hash (P2PKH) scheme. For Taproot keys, this will only watch
2880
// the BIP-0086 style output script. Use ImportTapscript for more advanced key
2881
// spend or script spend outputs.
2882
func (w *WalletKit) ImportPublicKey(_ context.Context,
2883
        req *ImportPublicKeyRequest) (*ImportPublicKeyResponse, error) {
4✔
2884

4✔
2885
        var (
4✔
2886
                pubKey *btcec.PublicKey
4✔
2887
                err    error
4✔
2888
        )
4✔
2889
        switch req.AddressType {
4✔
2890
        case AddressType_TAPROOT_PUBKEY:
4✔
2891
                pubKey, err = schnorr.ParsePubKey(req.PublicKey)
4✔
2892

2893
        default:
4✔
2894
                pubKey, err = btcec.ParsePubKey(req.PublicKey)
4✔
2895
        }
2896
        if err != nil {
4✔
2897
                return nil, err
×
2898
        }
×
2899

2900
        addrType, err := parseAddrType(req.AddressType, true)
4✔
2901
        if err != nil {
4✔
2902
                return nil, err
×
2903
        }
×
2904

2905
        if err := w.cfg.Wallet.ImportPublicKey(pubKey, *addrType); err != nil {
4✔
2906
                return nil, err
×
2907
        }
×
2908

2909
        return &ImportPublicKeyResponse{
4✔
2910
                Status: fmt.Sprintf("public key %x imported",
4✔
2911
                        pubKey.SerializeCompressed()),
4✔
2912
        }, nil
4✔
2913
}
2914

2915
// ImportTapscript imports a Taproot script and internal key and adds the
2916
// resulting Taproot output key as a watch-only output script into the wallet.
2917
// For BIP-0086 style Taproot keys (no root hash commitment and no script spend
2918
// path) use ImportPublicKey.
2919
//
2920
// NOTE: Taproot keys imported through this RPC currently _cannot_ be used for
2921
// funding PSBTs. Only tracking the balance and UTXOs is currently supported.
2922
func (w *WalletKit) ImportTapscript(_ context.Context,
2923
        req *ImportTapscriptRequest) (*ImportTapscriptResponse, error) {
4✔
2924

4✔
2925
        internalKey, err := schnorr.ParsePubKey(req.InternalPublicKey)
4✔
2926
        if err != nil {
4✔
2927
                return nil, fmt.Errorf("error parsing internal key: %w", err)
×
2928
        }
×
2929

2930
        var tapscript *waddrmgr.Tapscript
4✔
2931
        switch {
4✔
2932
        case req.GetFullTree() != nil:
4✔
2933
                tree := req.GetFullTree()
4✔
2934
                leaves := make([]txscript.TapLeaf, len(tree.AllLeaves))
4✔
2935
                for idx, leaf := range tree.AllLeaves {
8✔
2936
                        leaves[idx] = txscript.TapLeaf{
4✔
2937
                                LeafVersion: txscript.TapscriptLeafVersion(
4✔
2938
                                        leaf.LeafVersion,
4✔
2939
                                ),
4✔
2940
                                Script: leaf.Script,
4✔
2941
                        }
4✔
2942
                }
4✔
2943

2944
                tapscript = input.TapscriptFullTree(internalKey, leaves...)
4✔
2945

2946
        case req.GetPartialReveal() != nil:
4✔
2947
                partialReveal := req.GetPartialReveal()
4✔
2948
                if partialReveal.RevealedLeaf == nil {
4✔
2949
                        return nil, fmt.Errorf("missing revealed leaf")
×
2950
                }
×
2951

2952
                revealedLeaf := txscript.TapLeaf{
4✔
2953
                        LeafVersion: txscript.TapscriptLeafVersion(
4✔
2954
                                partialReveal.RevealedLeaf.LeafVersion,
4✔
2955
                        ),
4✔
2956
                        Script: partialReveal.RevealedLeaf.Script,
4✔
2957
                }
4✔
2958
                if len(partialReveal.FullInclusionProof)%32 != 0 {
4✔
2959
                        return nil, fmt.Errorf("invalid inclusion proof "+
×
2960
                                "length, expected multiple of 32, got %d",
×
2961
                                len(partialReveal.FullInclusionProof)%32)
×
2962
                }
×
2963

2964
                tapscript = input.TapscriptPartialReveal(
4✔
2965
                        internalKey, revealedLeaf,
4✔
2966
                        partialReveal.FullInclusionProof,
4✔
2967
                )
4✔
2968

2969
        case req.GetRootHashOnly() != nil:
4✔
2970
                rootHash := req.GetRootHashOnly()
4✔
2971
                if len(rootHash) == 0 {
4✔
2972
                        return nil, fmt.Errorf("missing root hash")
×
2973
                }
×
2974

2975
                tapscript = input.TapscriptRootHashOnly(internalKey, rootHash)
4✔
2976

2977
        case req.GetFullKeyOnly():
4✔
2978
                tapscript = input.TapscriptFullKeyOnly(internalKey)
4✔
2979

2980
        default:
×
2981
                return nil, fmt.Errorf("invalid script")
×
2982
        }
2983

2984
        taprootScope := waddrmgr.KeyScopeBIP0086
4✔
2985
        addr, err := w.cfg.Wallet.ImportTaprootScript(taprootScope, tapscript)
4✔
2986
        if err != nil {
4✔
2987
                return nil, fmt.Errorf("error importing script into wallet: %w",
×
2988
                        err)
×
2989
        }
×
2990

2991
        return &ImportTapscriptResponse{
4✔
2992
                P2TrAddress: addr.Address().String(),
4✔
2993
        }, nil
4✔
2994
}
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