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

lightningnetwork / lnd / 17832014233

18 Sep 2025 02:30PM UTC coverage: 57.196% (-9.4%) from 66.637%
17832014233

Pull #10133

github

web-flow
Merge 3e12b2767 into b34fc964b
Pull Request #10133: Add `XFindBaseLocalChanAlias` RPC

20 of 34 new or added lines in 4 files covered. (58.82%)

28528 existing lines in 459 files now uncovered.

99371 of 173739 relevant lines covered (57.2%)

1.78 hits per line

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

82.39
/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 {
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.AddrManager().WatchOnly() &&
3✔
96
                b.wallet.AddrManager().IsLocked() {
3✔
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(
3✔
105
                b.chainKeyScope,
3✔
106
        )
3✔
107
        if err != nil {
3✔
108
                return nil, err
×
109
        }
×
110

111
        b.lightningScope = lnScope
3✔
112

3✔
113
        return lnScope, nil
3✔
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 {
3✔
121

3✔
122
        // If this is the multi-sig key family, then we can return early as
3✔
123
        // this is the default account that's created.
3✔
124
        if keyFam == KeyFamilyMultiSig {
6✔
125
                return nil
3✔
126
        }
3✔
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))
3✔
131
        if err == nil {
6✔
132
                return nil
3✔
133
        }
3✔
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))
3✔
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) {
3✔
146
        var (
3✔
147
                pubKey *btcec.PublicKey
3✔
148
                keyLoc KeyLocator
3✔
149
        )
3✔
150

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

3✔
155
                scope, err := b.keyScope()
3✔
156
                if err != nil {
3✔
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)
3✔
164
                if err != nil {
3✔
165
                        return err
×
166
                }
×
167

168
                addrs, err := scope.NextExternalAddresses(
3✔
169
                        addrmgrNs, uint32(keyFam), 1,
3✔
170
                )
3✔
171
                if err != nil {
3✔
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)
3✔
178
                if !ok {
3✔
179
                        return fmt.Errorf("address is not a managed pubkey " +
×
180
                                "addr")
×
181
                }
×
182

183
                pubKey = addr.PubKey()
3✔
184

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

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

197
        return KeyDescriptor{
3✔
198
                PubKey:     pubKey,
3✔
199
                KeyLocator: keyLoc,
3✔
200
        }, nil
3✔
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) {
3✔
209
        var keyDesc KeyDescriptor
3✔
210

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

3✔
215
                scope, err := b.keyScope()
3✔
216
                if err != nil {
3✔
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() {
6✔
226
                        err = b.createAccountIfNotExists(
3✔
227
                                addrmgrNs, keyLoc.Family, scope,
3✔
228
                        )
3✔
229
                        if err != nil {
3✔
230
                                return err
×
231
                        }
×
232
                }
233

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

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

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

253
        return keyDesc, nil
3✔
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) {
3✔
262

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

3✔
265
        scope, err := b.keyScope()
3✔
266
        if err != nil {
3✔
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 {
6✔
274
                keyPath := waddrmgr.DerivationPath{
3✔
275
                        InternalAccount: uint32(keyDesc.Family),
3✔
276
                        Account:         uint32(keyDesc.Family),
3✔
277
                        Branch:          0,
3✔
278
                        Index:           keyDesc.Index,
3✔
279
                }
3✔
280
                privKey, err := scope.DeriveFromKeyPathCache(keyPath)
3✔
281
                if err == nil {
6✔
282
                        return privKey, nil
3✔
283
                }
3✔
284
        }
285

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

3✔
290
                // If the account doesn't exist, then we may need to create it
3✔
291
                // for the first time in order to derive the keys that we
3✔
292
                // require. We skip this if we're using a remote signer in which
3✔
293
                // case we _need_ to create all accounts when creating the
3✔
294
                // wallet, so it must exist now.
3✔
295
                if !b.wallet.AddrManager().WatchOnly() {
6✔
296
                        err = b.createAccountIfNotExists(
3✔
297
                                addrmgrNs, keyDesc.Family, scope,
3✔
298
                        )
3✔
299
                        if err != nil {
3✔
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 {
6✔
308
                        // Now that we know the account exists, we can safely
3✔
309
                        // derive the full private key from the given path.
3✔
310
                        path := waddrmgr.DerivationPath{
3✔
311
                                InternalAccount: uint32(keyDesc.Family),
3✔
312
                                Branch:          0,
3✔
313
                                Index:           keyDesc.Index,
3✔
314
                        }
3✔
315
                        addr, err := scope.DeriveFromKeyPath(addrmgrNs, path)
3✔
316
                        if err != nil {
3✔
317
                                return err
×
318
                        }
×
319

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

325
                        return nil
3✔
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{
3✔
332
                        InternalAccount: uint32(keyDesc.Family),
3✔
333
                        Branch:          0,
3✔
334
                        Index:           0,
3✔
335
                }
3✔
336

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

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

361
                                return nil
3✔
362
                        }
363

364
                        // This wasn't the target key, so roll forward and try
365
                        // the next one.
366
                        nextPath.Index++
3✔
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.
UNCOV
371
                return ErrCannotDerivePrivKey
×
372
        })
373
        if err != nil {
3✔
UNCOV
374
                return nil, err
×
UNCOV
375
        }
×
376

377
        return key, nil
3✔
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) {
3✔
391

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

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

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

3✔
408
        return h, nil
3✔
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,
416
        msg []byte, doubleHash bool) (*ecdsa.Signature, error) {
3✔
417

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

425
        var digest []byte
3✔
426
        if doubleHash {
6✔
427
                digest = chainhash.DoubleHashB(msg)
3✔
428
        } else {
6✔
429
                digest = chainhash.HashB(msg)
3✔
430
        }
3✔
431
        return ecdsa.Sign(privKey, digest), nil
3✔
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,
440
        msg []byte, doubleHash bool) ([]byte, error) {
3✔
441

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

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

456
        return ecdsa.SignCompact(privKey, digest, true), nil
3✔
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,
467
        tag []byte) (*schnorr.Signature, error) {
3✔
468

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

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

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