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

lightningnetwork / lnd / 16826702850

08 Aug 2025 09:15AM UTC coverage: 54.792% (-12.1%) from 66.893%
16826702850

Pull #10136

github

web-flow
Merge 572d16b03 into a3793b252
Pull Request #10136: lnwallet: use btcwallet's new interface

20 of 21 new or added lines in 2 files covered. (95.24%)

23889 existing lines in 294 files now uncovered.

108666 of 198325 relevant lines covered (54.79%)

22097.11 hits per line

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

68.31
/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.Interface
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.Interface, coinType uint32) SecretKeyRing {
12✔
68
        // Construct the key scope that will be used within the waddrmgr to
12✔
69
        // create an HD chain for deriving all of our required keys. A different
12✔
70
        // scope is used for each specific coin type.
12✔
71
        chainKeyScope := waddrmgr.KeyScope{
12✔
72
                Purpose: BIP0043Purpose,
12✔
73
                Coin:    coinType,
12✔
74
        }
12✔
75

12✔
76
        return &BtcWalletKeyRing{
12✔
77
                wallet:        w,
12✔
78
                chainKeyScope: chainKeyScope,
12✔
79
        }
12✔
80
}
12✔
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) {
715✔
87
        // If the scope has already been populated, then we'll return it
715✔
88
        // directly.
715✔
89
        if b.lightningScope != nil {
1,418✔
90
                return b.lightningScope, nil
703✔
91
        }
703✔
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.AddrManager().WatchOnly() &&
12✔
96
                b.wallet.AddrManager().IsLocked() {
12✔
NEW
97

×
98
                return nil, fmt.Errorf("cannot create BtcWalletKeyRing with " +
×
99
                        "locked waddrmgr.Manager")
×
100
        }
×
101

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

111
        b.lightningScope = lnScope
12✔
112

12✔
113
        return lnScope, nil
12✔
114
}
115

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

695✔
122
        // If this is the multi-sig key family, then we can return early as
695✔
123
        // this is the default account that's created.
695✔
124
        if keyFam == KeyFamilyMultiSig {
794✔
125
                return nil
99✔
126
        }
99✔
127

128
        // Otherwise, we'll check if the account already exists, if so, we can
129
        // once again bail early.
130
        _, err := scope.AccountName(addrmgrNs, uint32(keyFam))
596✔
131
        if err == nil {
1,156✔
132
                return nil
560✔
133
        }
560✔
134

135
        // If we reach this point, then the account hasn't yet been created, so
136
        // we'll need to create it before we can proceed.
137
        return scope.NewRawAccount(addrmgrNs, uint32(keyFam))
36✔
138
}
139

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

331✔
151
        db := b.wallet.Database()
331✔
152
        err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
662✔
153
                addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
331✔
154

331✔
155
                scope, err := b.keyScope()
331✔
156
                if err != nil {
331✔
157
                        return err
×
158
                }
×
159

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

168
                addrs, err := scope.NextExternalAddresses(
331✔
169
                        addrmgrNs, uint32(keyFam), 1,
331✔
170
                )
331✔
171
                if err != nil {
331✔
172
                        return err
×
173
                }
×
174

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

183
                pubKey = addr.PubKey()
331✔
184

331✔
185
                _, pathInfo, _ := addr.DerivationInfo()
331✔
186
                keyLoc = KeyLocator{
331✔
187
                        Family: keyFam,
331✔
188
                        Index:  pathInfo.Index,
331✔
189
                }
331✔
190

331✔
191
                return nil
331✔
192
        })
193
        if err != nil {
331✔
194
                return KeyDescriptor{}, err
×
195
        }
×
196

197
        return KeyDescriptor{
331✔
198
                PubKey:     pubKey,
331✔
199
                KeyLocator: keyLoc,
331✔
200
        }, nil
331✔
201
}
202

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

280✔
211
        db := b.wallet.Database()
280✔
212
        err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
560✔
213
                addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
280✔
214

280✔
215
                scope, err := b.keyScope()
280✔
216
                if err != nil {
280✔
217
                        return err
×
218
                }
×
219

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

234
                path := waddrmgr.DerivationPath{
280✔
235
                        InternalAccount: uint32(keyLoc.Family),
280✔
236
                        Branch:          0,
280✔
237
                        Index:           keyLoc.Index,
280✔
238
                }
280✔
239
                addr, err := scope.DeriveFromKeyPath(addrmgrNs, path)
280✔
240
                if err != nil {
280✔
241
                        return err
×
242
                }
×
243

244
                keyDesc.KeyLocator = keyLoc
280✔
245
                keyDesc.PubKey = addr.(waddrmgr.ManagedPubKeyAddress).PubKey()
280✔
246

280✔
247
                return nil
280✔
248
        })
249
        if err != nil {
280✔
250
                return keyDesc, err
×
251
        }
×
252

253
        return keyDesc, nil
280✔
254
}
255

256
// DerivePrivKey attempts to derive the private key that corresponds to the
257
// passed key descriptor.
258
//
259
// NOTE: This is part of the keychain.SecretKeyRing interface.
260
func (b *BtcWalletKeyRing) DerivePrivKey(keyDesc KeyDescriptor) (
261
        *btcec.PrivateKey, error) {
104✔
262

104✔
263
        var key *btcec.PrivateKey
104✔
264

104✔
265
        scope, err := b.keyScope()
104✔
266
        if err != nil {
104✔
267
                return nil, err
×
268
        }
×
269

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

286
        db := b.wallet.Database()
84✔
287
        err = walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
168✔
288
                addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
84✔
289

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

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

320
                        key, err = addr.(waddrmgr.ManagedPubKeyAddress).PrivKey()
44✔
321
                        if err != nil {
44✔
322
                                return err
×
323
                        }
×
324

325
                        return nil
44✔
326
                }
327

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

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

80✔
353
                        // If this is the target public key, then we'll return
80✔
354
                        // it directly back to the caller.
80✔
355
                        if managedAddr.PubKey().IsEqual(keyDesc.PubKey) {
100✔
356
                                key, err = managedAddr.PrivKey()
20✔
357
                                if err != nil {
20✔
358
                                        return err
×
359
                                }
×
360

361
                                return nil
20✔
362
                        }
363

364
                        // This wasn't the target key, so roll forward and try
365
                        // the next one.
366
                        nextPath.Index++
60✔
367
                }
368

369
                // If we reach this point, then we we're unable to derive the
370
                // private key, so return an error back to the user.
371
                return ErrCannotDerivePrivKey
20✔
372
        })
373
        if err != nil {
104✔
374
                return nil, err
20✔
375
        }
20✔
376

377
        return key, nil
64✔
378
}
379

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

44✔
392
        privKey, err := b.DerivePrivKey(keyDesc)
44✔
393
        if err != nil {
44✔
394
                return [32]byte{}, err
×
395
        }
×
396

397
        var (
44✔
398
                pubJacobian btcec.JacobianPoint
44✔
399
                s           btcec.JacobianPoint
44✔
400
        )
44✔
401
        pub.AsJacobian(&pubJacobian)
44✔
402

44✔
403
        btcec.ScalarMultNonConst(&privKey.Key, &pubJacobian, &s)
44✔
404
        s.ToAffine()
44✔
405
        sPubKey := btcec.NewPublicKey(&s.X, &s.Y)
44✔
406
        h := sha256.Sum256(sPubKey.SerializeCompressed())
44✔
407

44✔
408
        return h, nil
44✔
409
}
410

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

×
UNCOV
418
        privKey, err := b.DerivePrivKey(KeyDescriptor{
×
UNCOV
419
                KeyLocator: keyLoc,
×
UNCOV
420
        })
×
UNCOV
421
        if err != nil {
×
422
                return nil, err
×
423
        }
×
424

UNCOV
425
        var digest []byte
×
UNCOV
426
        if doubleHash {
×
UNCOV
427
                digest = chainhash.DoubleHashB(msg)
×
UNCOV
428
        } else {
×
UNCOV
429
                digest = chainhash.HashB(msg)
×
UNCOV
430
        }
×
UNCOV
431
        return ecdsa.Sign(privKey, digest), nil
×
432
}
433

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

×
UNCOV
442
        privKey, err := b.DerivePrivKey(KeyDescriptor{
×
UNCOV
443
                KeyLocator: keyLoc,
×
UNCOV
444
        })
×
UNCOV
445
        if err != nil {
×
446
                return nil, err
×
447
        }
×
448

UNCOV
449
        var digest []byte
×
UNCOV
450
        if doubleHash {
×
UNCOV
451
                digest = chainhash.DoubleHashB(msg)
×
UNCOV
452
        } else {
×
UNCOV
453
                digest = chainhash.HashB(msg)
×
UNCOV
454
        }
×
455

UNCOV
456
        return ecdsa.SignCompact(privKey, digest, true), nil
×
457
}
458

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

×
UNCOV
469
        privKey, err := b.DerivePrivKey(KeyDescriptor{
×
UNCOV
470
                KeyLocator: keyLoc,
×
UNCOV
471
        })
×
UNCOV
472
        if err != nil {
×
473
                return nil, err
×
474
        }
×
475

UNCOV
476
        if len(taprootTweak) > 0 {
×
UNCOV
477
                privKey = txscript.TweakTaprootPrivKey(*privKey, taprootTweak)
×
UNCOV
478
        }
×
479

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