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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

1.81 hits per line

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

82.5
/keychain/btcwallet.go
1
package keychain
2

3
import (
4
        "crypto/sha256"
5
        "fmt"
6

7
        "github.com/btcsuite/btcd/btcec/v2"
8
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
9
        "github.com/btcsuite/btcd/btcec/v2/schnorr"
10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/txscript"
12
        "github.com/btcsuite/btcwallet/waddrmgr"
13
        "github.com/btcsuite/btcwallet/wallet"
14
        "github.com/btcsuite/btcwallet/walletdb"
15
)
16

17
const (
18
        // CoinTypeBitcoin specifies the BIP44 coin type for Bitcoin key
19
        // derivation.
20
        CoinTypeBitcoin uint32 = 0
21

22
        // CoinTypeTestnet specifies the BIP44 coin type for all testnet key
23
        // derivation.
24
        CoinTypeTestnet = 1
25
)
26

27
var (
28
        // lightningAddrSchema is the scope addr schema for all keys that we
29
        // derive. We'll treat them all as p2wkh addresses, as atm we must
30
        // specify a particular type.
31
        lightningAddrSchema = waddrmgr.ScopeAddrSchema{
32
                ExternalAddrType: waddrmgr.WitnessPubKey,
33
                InternalAddrType: waddrmgr.WitnessPubKey,
34
        }
35

36
        // waddrmgrNamespaceKey is the namespace key that the waddrmgr state is
37
        // stored within the top-level waleltdb buckets of btcwallet.
38
        waddrmgrNamespaceKey = []byte("waddrmgr")
39
)
40

41
// BtcWalletKeyRing is an implementation of both the KeyRing and SecretKeyRing
42
// interfaces backed by btcwallet's internal root waddrmgr. Internally, we'll
43
// be using a ScopedKeyManager to do all of our derivations, using the key
44
// scope and scope addr scehma defined above. Re-using the existing key scope
45
// construction means that all key derivation will be protected under the root
46
// seed of the wallet, making each derived key fully deterministic.
47
type BtcWalletKeyRing struct {
48
        // wallet is a pointer to the active instance of the btcwallet core.
49
        // This is required as we'll need to manually open database
50
        // transactions in order to derive addresses and lookup relevant keys
51
        wallet *wallet.Wallet
52

53
        // chainKeyScope defines the purpose and coin type to be used when generating
54
        // keys for this keyring.
55
        chainKeyScope waddrmgr.KeyScope
56

57
        // lightningScope is a pointer to the scope that we'll be using as a
58
        // sub key manager to derive all the keys that we require.
59
        lightningScope *waddrmgr.ScopedKeyManager
60
}
61

62
// NewBtcWalletKeyRing creates a new implementation of the
63
// keychain.SecretKeyRing interface backed by btcwallet.
64
//
65
// NOTE: The passed waddrmgr.Manager MUST be unlocked in order for the keychain
66
// to function.
67
func NewBtcWalletKeyRing(w *wallet.Wallet, coinType uint32) SecretKeyRing {
3✔
68
        // Construct the key scope that will be used within the waddrmgr to
3✔
69
        // create an HD chain for deriving all of our required keys. A different
3✔
70
        // scope is used for each specific coin type.
3✔
71
        chainKeyScope := waddrmgr.KeyScope{
3✔
72
                Purpose: BIP0043Purpose,
3✔
73
                Coin:    coinType,
3✔
74
        }
3✔
75

3✔
76
        return &BtcWalletKeyRing{
3✔
77
                wallet:        w,
3✔
78
                chainKeyScope: chainKeyScope,
3✔
79
        }
3✔
80
}
3✔
81

82
// keyScope attempts to return the key scope that we'll use to derive all of
83
// our keys. If the scope has already been fetched from the database, then a
84
// cached version will be returned. Otherwise, we'll fetch it from the database
85
// and cache it for subsequent accesses.
86
func (b *BtcWalletKeyRing) keyScope() (*waddrmgr.ScopedKeyManager, error) {
3✔
87
        // If the scope has already been populated, then we'll return it
3✔
88
        // directly.
3✔
89
        if b.lightningScope != nil {
6✔
90
                return b.lightningScope, nil
3✔
91
        }
3✔
92

93
        // Otherwise, we'll first do a check to ensure that the root manager
94
        // isn't locked, as otherwise we won't be able to *use* the scope.
95
        if !b.wallet.Manager.WatchOnly() && b.wallet.Manager.IsLocked() {
3✔
96
                return nil, fmt.Errorf("cannot create BtcWalletKeyRing with " +
×
97
                        "locked waddrmgr.Manager")
×
98
        }
×
99

100
        // If the manager is indeed unlocked, then we'll fetch the scope, cache
101
        // it, and return to the caller.
102
        lnScope, err := b.wallet.Manager.FetchScopedKeyManager(b.chainKeyScope)
3✔
103
        if err != nil {
3✔
104
                return nil, err
×
105
        }
×
106

107
        b.lightningScope = lnScope
3✔
108

3✔
109
        return lnScope, nil
3✔
110
}
111

112
// createAccountIfNotExists will create the corresponding account for a key
113
// family if it doesn't already exist in the database.
114
func (b *BtcWalletKeyRing) createAccountIfNotExists(
115
        addrmgrNs walletdb.ReadWriteBucket, keyFam KeyFamily,
116
        scope *waddrmgr.ScopedKeyManager) error {
3✔
117

3✔
118
        // If this is the multi-sig key family, then we can return early as
3✔
119
        // this is the default account that's created.
3✔
120
        if keyFam == KeyFamilyMultiSig {
6✔
121
                return nil
3✔
122
        }
3✔
123

124
        // Otherwise, we'll check if the account already exists, if so, we can
125
        // once again bail early.
126
        _, err := scope.AccountName(addrmgrNs, uint32(keyFam))
3✔
127
        if err == nil {
6✔
128
                return nil
3✔
129
        }
3✔
130

131
        // If we reach this point, then the account hasn't yet been created, so
132
        // we'll need to create it before we can proceed.
133
        return scope.NewRawAccount(addrmgrNs, uint32(keyFam))
3✔
134
}
135

136
// DeriveNextKey attempts to derive the *next* key within the key family
137
// (account in BIP43) specified. This method should return the next external
138
// child within this branch.
139
//
140
// NOTE: This is part of the keychain.KeyRing interface.
141
func (b *BtcWalletKeyRing) DeriveNextKey(keyFam KeyFamily) (KeyDescriptor, error) {
3✔
142
        var (
3✔
143
                pubKey *btcec.PublicKey
3✔
144
                keyLoc KeyLocator
3✔
145
        )
3✔
146

3✔
147
        db := b.wallet.Database()
3✔
148
        err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
6✔
149
                addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
3✔
150

3✔
151
                scope, err := b.keyScope()
3✔
152
                if err != nil {
3✔
153
                        return err
×
154
                }
×
155

156
                // If the account doesn't exist, then we may need to create it
157
                // for the first time in order to derive the keys that we
158
                // require.
159
                err = b.createAccountIfNotExists(addrmgrNs, keyFam, scope)
3✔
160
                if err != nil {
3✔
161
                        return err
×
162
                }
×
163

164
                addrs, err := scope.NextExternalAddresses(
3✔
165
                        addrmgrNs, uint32(keyFam), 1,
3✔
166
                )
3✔
167
                if err != nil {
3✔
168
                        return err
×
169
                }
×
170

171
                // Extract the first address, ensuring that it is of the proper
172
                // interface type, otherwise we can't manipulate it below.
173
                addr, ok := addrs[0].(waddrmgr.ManagedPubKeyAddress)
3✔
174
                if !ok {
3✔
175
                        return fmt.Errorf("address is not a managed pubkey " +
×
176
                                "addr")
×
177
                }
×
178

179
                pubKey = addr.PubKey()
3✔
180

3✔
181
                _, pathInfo, _ := addr.DerivationInfo()
3✔
182
                keyLoc = KeyLocator{
3✔
183
                        Family: keyFam,
3✔
184
                        Index:  pathInfo.Index,
3✔
185
                }
3✔
186

3✔
187
                return nil
3✔
188
        })
189
        if err != nil {
3✔
190
                return KeyDescriptor{}, err
×
191
        }
×
192

193
        return KeyDescriptor{
3✔
194
                PubKey:     pubKey,
3✔
195
                KeyLocator: keyLoc,
3✔
196
        }, nil
3✔
197
}
198

199
// DeriveKey attempts to derive an arbitrary key specified by the passed
200
// KeyLocator. This may be used in several recovery scenarios, or when manually
201
// rotating something like our current default node key.
202
//
203
// NOTE: This is part of the keychain.KeyRing interface.
204
func (b *BtcWalletKeyRing) DeriveKey(keyLoc KeyLocator) (KeyDescriptor, error) {
3✔
205
        var keyDesc KeyDescriptor
3✔
206

3✔
207
        db := b.wallet.Database()
3✔
208
        err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
6✔
209
                addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
3✔
210

3✔
211
                scope, err := b.keyScope()
3✔
212
                if err != nil {
3✔
213
                        return err
×
214
                }
×
215

216
                // If the account doesn't exist, then we may need to create it
217
                // for the first time in order to derive the keys that we
218
                // require. We skip this if we're using a remote signer in which
219
                // case we _need_ to create all accounts when creating the
220
                // wallet, so it must exist now.
221
                if !b.wallet.Manager.WatchOnly() {
6✔
222
                        err = b.createAccountIfNotExists(
3✔
223
                                addrmgrNs, keyLoc.Family, scope,
3✔
224
                        )
3✔
225
                        if err != nil {
3✔
226
                                return err
×
227
                        }
×
228
                }
229

230
                path := waddrmgr.DerivationPath{
3✔
231
                        InternalAccount: uint32(keyLoc.Family),
3✔
232
                        Branch:          0,
3✔
233
                        Index:           keyLoc.Index,
3✔
234
                }
3✔
235
                addr, err := scope.DeriveFromKeyPath(addrmgrNs, path)
3✔
236
                if err != nil {
3✔
237
                        return err
×
238
                }
×
239

240
                keyDesc.KeyLocator = keyLoc
3✔
241
                keyDesc.PubKey = addr.(waddrmgr.ManagedPubKeyAddress).PubKey()
3✔
242

3✔
243
                return nil
3✔
244
        })
245
        if err != nil {
3✔
246
                return keyDesc, err
×
247
        }
×
248

249
        return keyDesc, nil
3✔
250
}
251

252
// DerivePrivKey attempts to derive the private key that corresponds to the
253
// passed key descriptor.
254
//
255
// NOTE: This is part of the keychain.SecretKeyRing interface.
256
func (b *BtcWalletKeyRing) DerivePrivKey(keyDesc KeyDescriptor) (
257
        *btcec.PrivateKey, error) {
3✔
258

3✔
259
        var key *btcec.PrivateKey
3✔
260

3✔
261
        scope, err := b.keyScope()
3✔
262
        if err != nil {
3✔
263
                return nil, err
×
264
        }
×
265

266
        // First, attempt to see if we can read the key directly from
267
        // btcwallet's internal cache, if we can then we can skip all the
268
        // operations below (fast path).
269
        if keyDesc.PubKey == nil {
6✔
270
                keyPath := waddrmgr.DerivationPath{
3✔
271
                        InternalAccount: uint32(keyDesc.Family),
3✔
272
                        Account:         uint32(keyDesc.Family),
3✔
273
                        Branch:          0,
3✔
274
                        Index:           keyDesc.Index,
3✔
275
                }
3✔
276
                privKey, err := scope.DeriveFromKeyPathCache(keyPath)
3✔
277
                if err == nil {
6✔
278
                        return privKey, nil
3✔
279
                }
3✔
280
        }
281

282
        db := b.wallet.Database()
3✔
283
        err = walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
6✔
284
                addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
3✔
285

3✔
286
                // If the account doesn't exist, then we may need to create it
3✔
287
                // for the first time in order to derive the keys that we
3✔
288
                // require. We skip this if we're using a remote signer in which
3✔
289
                // case we _need_ to create all accounts when creating the
3✔
290
                // wallet, so it must exist now.
3✔
291
                if !b.wallet.Manager.WatchOnly() {
6✔
292
                        err = b.createAccountIfNotExists(
3✔
293
                                addrmgrNs, keyDesc.Family, scope,
3✔
294
                        )
3✔
295
                        if err != nil {
3✔
296
                                return err
×
297
                        }
×
298
                }
299

300
                // If the public key isn't set or they have a non-zero index,
301
                // then we know that the caller instead knows the derivation
302
                // path for a key.
303
                if keyDesc.PubKey == nil || keyDesc.Index > 0 {
6✔
304
                        // Now that we know the account exists, we can safely
3✔
305
                        // derive the full private key from the given path.
3✔
306
                        path := waddrmgr.DerivationPath{
3✔
307
                                InternalAccount: uint32(keyDesc.Family),
3✔
308
                                Branch:          0,
3✔
309
                                Index:           keyDesc.Index,
3✔
310
                        }
3✔
311
                        addr, err := scope.DeriveFromKeyPath(addrmgrNs, path)
3✔
312
                        if err != nil {
3✔
313
                                return err
×
314
                        }
×
315

316
                        key, err = addr.(waddrmgr.ManagedPubKeyAddress).PrivKey()
3✔
317
                        if err != nil {
3✔
318
                                return err
×
319
                        }
×
320

321
                        return nil
3✔
322
                }
323

324
                // If the public key isn't nil, then this indicates that we
325
                // need to scan for the private key, assuming that we know the
326
                // valid key family.
327
                nextPath := waddrmgr.DerivationPath{
3✔
328
                        InternalAccount: uint32(keyDesc.Family),
3✔
329
                        Branch:          0,
3✔
330
                        Index:           0,
3✔
331
                }
3✔
332

3✔
333
                // We'll now iterate through our key range in an attempt to
3✔
334
                // find the target public key.
3✔
335
                //
3✔
336
                // TODO(roasbeef): possibly move scanning into wallet to allow
3✔
337
                // to be parallelized
3✔
338
                for i := 0; i < MaxKeyRangeScan; i++ {
6✔
339
                        // Derive the next key in the range and fetch its
3✔
340
                        // managed address.
3✔
341
                        addr, err := scope.DeriveFromKeyPath(
3✔
342
                                addrmgrNs, nextPath,
3✔
343
                        )
3✔
344
                        if err != nil {
3✔
345
                                return err
×
346
                        }
×
347
                        managedAddr := addr.(waddrmgr.ManagedPubKeyAddress)
3✔
348

3✔
349
                        // If this is the target public key, then we'll return
3✔
350
                        // it directly back to the caller.
3✔
351
                        if managedAddr.PubKey().IsEqual(keyDesc.PubKey) {
6✔
352
                                key, err = managedAddr.PrivKey()
3✔
353
                                if err != nil {
3✔
354
                                        return err
×
355
                                }
×
356

357
                                return nil
3✔
358
                        }
359

360
                        // This wasn't the target key, so roll forward and try
361
                        // the next one.
362
                        nextPath.Index++
3✔
363
                }
364

365
                // If we reach this point, then we we're unable to derive the
366
                // private key, so return an error back to the user.
UNCOV
367
                return ErrCannotDerivePrivKey
×
368
        })
369
        if err != nil {
3✔
UNCOV
370
                return nil, err
×
UNCOV
371
        }
×
372

373
        return key, nil
3✔
374
}
375

376
// ECDH performs a scalar multiplication (ECDH-like operation) between the
377
// target key descriptor and remote public key. The output returned will be
378
// the sha256 of the resulting shared point serialized in compressed format. If
379
// k is our private key, and P is the public key, we perform the following
380
// operation:
381
//
382
//        sx := k*P s := sha256(sx.SerializeCompressed())
383
//
384
// NOTE: This is part of the keychain.ECDHRing interface.
385
func (b *BtcWalletKeyRing) ECDH(keyDesc KeyDescriptor,
386
        pub *btcec.PublicKey) ([32]byte, error) {
3✔
387

3✔
388
        privKey, err := b.DerivePrivKey(keyDesc)
3✔
389
        if err != nil {
3✔
390
                return [32]byte{}, err
×
391
        }
×
392

393
        var (
3✔
394
                pubJacobian btcec.JacobianPoint
3✔
395
                s           btcec.JacobianPoint
3✔
396
        )
3✔
397
        pub.AsJacobian(&pubJacobian)
3✔
398

3✔
399
        btcec.ScalarMultNonConst(&privKey.Key, &pubJacobian, &s)
3✔
400
        s.ToAffine()
3✔
401
        sPubKey := btcec.NewPublicKey(&s.X, &s.Y)
3✔
402
        h := sha256.Sum256(sPubKey.SerializeCompressed())
3✔
403

3✔
404
        return h, nil
3✔
405
}
406

407
// SignMessage signs the given message, single or double SHA256 hashing it
408
// first, with the private key described in the key locator.
409
//
410
// NOTE: This is part of the keychain.MessageSignerRing interface.
411
func (b *BtcWalletKeyRing) SignMessage(keyLoc KeyLocator,
412
        msg []byte, doubleHash bool) (*ecdsa.Signature, error) {
3✔
413

3✔
414
        privKey, err := b.DerivePrivKey(KeyDescriptor{
3✔
415
                KeyLocator: keyLoc,
3✔
416
        })
3✔
417
        if err != nil {
3✔
418
                return nil, err
×
419
        }
×
420

421
        var digest []byte
3✔
422
        if doubleHash {
6✔
423
                digest = chainhash.DoubleHashB(msg)
3✔
424
        } else {
6✔
425
                digest = chainhash.HashB(msg)
3✔
426
        }
3✔
427
        return ecdsa.Sign(privKey, digest), nil
3✔
428
}
429

430
// SignMessageCompact signs the given message, single or double SHA256 hashing
431
// it first, with the private key described in the key locator and returns
432
// the signature in the compact, public key recoverable format.
433
//
434
// NOTE: This is part of the keychain.MessageSignerRing interface.
435
func (b *BtcWalletKeyRing) SignMessageCompact(keyLoc KeyLocator,
436
        msg []byte, doubleHash bool) ([]byte, error) {
3✔
437

3✔
438
        privKey, err := b.DerivePrivKey(KeyDescriptor{
3✔
439
                KeyLocator: keyLoc,
3✔
440
        })
3✔
441
        if err != nil {
3✔
442
                return nil, err
×
443
        }
×
444

445
        var digest []byte
3✔
446
        if doubleHash {
6✔
447
                digest = chainhash.DoubleHashB(msg)
3✔
448
        } else {
6✔
449
                digest = chainhash.HashB(msg)
3✔
450
        }
3✔
451

452
        return ecdsa.SignCompact(privKey, digest, true), nil
3✔
453
}
454

455
// SignMessageSchnorr uses the Schnorr signature algorithm to sign the given
456
// message, single or double SHA256 hashing it first, with the private key
457
// described in the key locator and the optional tweak applied to the private
458
// key.
459
//
460
// NOTE: This is part of the keychain.MessageSignerRing interface.
461
func (b *BtcWalletKeyRing) SignMessageSchnorr(keyLoc KeyLocator,
462
        msg []byte, doubleHash bool, taprootTweak []byte,
463
        tag []byte) (*schnorr.Signature, error) {
3✔
464

3✔
465
        privKey, err := b.DerivePrivKey(KeyDescriptor{
3✔
466
                KeyLocator: keyLoc,
3✔
467
        })
3✔
468
        if err != nil {
3✔
469
                return nil, err
×
470
        }
×
471

472
        if len(taprootTweak) > 0 {
6✔
473
                privKey = txscript.TweakTaprootPrivKey(*privKey, taprootTweak)
3✔
474
        }
3✔
475

476
        // If a tag was provided, we need to take the tagged hash of the input.
477
        var digest []byte
3✔
478
        switch {
3✔
479
        case len(tag) > 0:
3✔
480
                taggedHash := chainhash.TaggedHash(tag, msg)
3✔
481
                digest = taggedHash[:]
3✔
482
        case doubleHash:
×
483
                digest = chainhash.DoubleHashB(msg)
×
484
        default:
3✔
485
                digest = chainhash.HashB(msg)
3✔
486
        }
487
        return schnorr.Sign(privKey, digest)
3✔
488
}
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