-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
btcwallet.go
487 lines (418 loc) · 14 KB
/
btcwallet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package keychain
import (
"crypto/sha256"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/walletdb"
)
const (
// CoinTypeBitcoin specifies the BIP44 coin type for Bitcoin key
// derivation.
CoinTypeBitcoin uint32 = 0
// CoinTypeTestnet specifies the BIP44 coin type for all testnet key
// derivation.
CoinTypeTestnet = 1
)
var (
// lightningAddrSchema is the scope addr schema for all keys that we
// derive. We'll treat them all as p2wkh addresses, as atm we must
// specify a particular type.
lightningAddrSchema = waddrmgr.ScopeAddrSchema{
ExternalAddrType: waddrmgr.WitnessPubKey,
InternalAddrType: waddrmgr.WitnessPubKey,
}
// waddrmgrNamespaceKey is the namespace key that the waddrmgr state is
// stored within the top-level waleltdb buckets of btcwallet.
waddrmgrNamespaceKey = []byte("waddrmgr")
)
// BtcWalletKeyRing is an implementation of both the KeyRing and SecretKeyRing
// interfaces backed by btcwallet's internal root waddrmgr. Internally, we'll
// be using a ScopedKeyManager to do all of our derivations, using the key
// scope and scope addr scehma defined above. Re-using the existing key scope
// construction means that all key derivation will be protected under the root
// seed of the wallet, making each derived key fully deterministic.
type BtcWalletKeyRing struct {
// wallet is a pointer to the active instance of the btcwallet core.
// This is required as we'll need to manually open database
// transactions in order to derive addresses and lookup relevant keys
wallet *wallet.Wallet
// chainKeyScope defines the purpose and coin type to be used when generating
// keys for this keyring.
chainKeyScope waddrmgr.KeyScope
// lightningScope is a pointer to the scope that we'll be using as a
// sub key manager to derive all the keys that we require.
lightningScope *waddrmgr.ScopedKeyManager
}
// NewBtcWalletKeyRing creates a new implementation of the
// keychain.SecretKeyRing interface backed by btcwallet.
//
// NOTE: The passed waddrmgr.Manager MUST be unlocked in order for the keychain
// to function.
func NewBtcWalletKeyRing(w *wallet.Wallet, coinType uint32) SecretKeyRing {
// Construct the key scope that will be used within the waddrmgr to
// create an HD chain for deriving all of our required keys. A different
// scope is used for each specific coin type.
chainKeyScope := waddrmgr.KeyScope{
Purpose: BIP0043Purpose,
Coin: coinType,
}
return &BtcWalletKeyRing{
wallet: w,
chainKeyScope: chainKeyScope,
}
}
// keyScope attempts to return the key scope that we'll use to derive all of
// our keys. If the scope has already been fetched from the database, then a
// cached version will be returned. Otherwise, we'll fetch it from the database
// and cache it for subsequent accesses.
func (b *BtcWalletKeyRing) keyScope() (*waddrmgr.ScopedKeyManager, error) {
// If the scope has already been populated, then we'll return it
// directly.
if b.lightningScope != nil {
return b.lightningScope, nil
}
// Otherwise, we'll first do a check to ensure that the root manager
// isn't locked, as otherwise we won't be able to *use* the scope.
if !b.wallet.Manager.WatchOnly() && b.wallet.Manager.IsLocked() {
return nil, fmt.Errorf("cannot create BtcWalletKeyRing with " +
"locked waddrmgr.Manager")
}
// If the manager is indeed unlocked, then we'll fetch the scope, cache
// it, and return to the caller.
lnScope, err := b.wallet.Manager.FetchScopedKeyManager(b.chainKeyScope)
if err != nil {
return nil, err
}
b.lightningScope = lnScope
return lnScope, nil
}
// createAccountIfNotExists will create the corresponding account for a key
// family if it doesn't already exist in the database.
func (b *BtcWalletKeyRing) createAccountIfNotExists(
addrmgrNs walletdb.ReadWriteBucket, keyFam KeyFamily,
scope *waddrmgr.ScopedKeyManager) error {
// If this is the multi-sig key family, then we can return early as
// this is the default account that's created.
if keyFam == KeyFamilyMultiSig {
return nil
}
// Otherwise, we'll check if the account already exists, if so, we can
// once again bail early.
_, err := scope.AccountName(addrmgrNs, uint32(keyFam))
if err == nil {
return nil
}
// If we reach this point, then the account hasn't yet been created, so
// we'll need to create it before we can proceed.
return scope.NewRawAccount(addrmgrNs, uint32(keyFam))
}
// DeriveNextKey attempts to derive the *next* key within the key family
// (account in BIP43) specified. This method should return the next external
// child within this branch.
//
// NOTE: This is part of the keychain.KeyRing interface.
func (b *BtcWalletKeyRing) DeriveNextKey(keyFam KeyFamily) (KeyDescriptor, error) {
var (
pubKey *btcec.PublicKey
keyLoc KeyLocator
)
db := b.wallet.Database()
err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
scope, err := b.keyScope()
if err != nil {
return err
}
// If the account doesn't exist, then we may need to create it
// for the first time in order to derive the keys that we
// require.
err = b.createAccountIfNotExists(addrmgrNs, keyFam, scope)
if err != nil {
return err
}
addrs, err := scope.NextExternalAddresses(
addrmgrNs, uint32(keyFam), 1,
)
if err != nil {
return err
}
// Extract the first address, ensuring that it is of the proper
// interface type, otherwise we can't manipulate it below.
addr, ok := addrs[0].(waddrmgr.ManagedPubKeyAddress)
if !ok {
return fmt.Errorf("address is not a managed pubkey " +
"addr")
}
pubKey = addr.PubKey()
_, pathInfo, _ := addr.DerivationInfo()
keyLoc = KeyLocator{
Family: keyFam,
Index: pathInfo.Index,
}
return nil
})
if err != nil {
return KeyDescriptor{}, err
}
return KeyDescriptor{
PubKey: pubKey,
KeyLocator: keyLoc,
}, nil
}
// DeriveKey attempts to derive an arbitrary key specified by the passed
// KeyLocator. This may be used in several recovery scenarios, or when manually
// rotating something like our current default node key.
//
// NOTE: This is part of the keychain.KeyRing interface.
func (b *BtcWalletKeyRing) DeriveKey(keyLoc KeyLocator) (KeyDescriptor, error) {
var keyDesc KeyDescriptor
db := b.wallet.Database()
err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
scope, err := b.keyScope()
if err != nil {
return err
}
// If the account doesn't exist, then we may need to create it
// for the first time in order to derive the keys that we
// require. We skip this if we're using a remote signer in which
// case we _need_ to create all accounts when creating the
// wallet, so it must exist now.
if !b.wallet.Manager.WatchOnly() {
err = b.createAccountIfNotExists(
addrmgrNs, keyLoc.Family, scope,
)
if err != nil {
return err
}
}
path := waddrmgr.DerivationPath{
InternalAccount: uint32(keyLoc.Family),
Branch: 0,
Index: keyLoc.Index,
}
addr, err := scope.DeriveFromKeyPath(addrmgrNs, path)
if err != nil {
return err
}
keyDesc.KeyLocator = keyLoc
keyDesc.PubKey = addr.(waddrmgr.ManagedPubKeyAddress).PubKey()
return nil
})
if err != nil {
return keyDesc, err
}
return keyDesc, nil
}
// DerivePrivKey attempts to derive the private key that corresponds to the
// passed key descriptor.
//
// NOTE: This is part of the keychain.SecretKeyRing interface.
func (b *BtcWalletKeyRing) DerivePrivKey(keyDesc KeyDescriptor) (
*btcec.PrivateKey, error) {
var key *btcec.PrivateKey
scope, err := b.keyScope()
if err != nil {
return nil, err
}
// First, attempt to see if we can read the key directly from
// btcwallet's internal cache, if we can then we can skip all the
// operations below (fast path).
if keyDesc.PubKey == nil {
keyPath := waddrmgr.DerivationPath{
InternalAccount: uint32(keyDesc.Family),
Account: uint32(keyDesc.Family),
Branch: 0,
Index: keyDesc.Index,
}
privKey, err := scope.DeriveFromKeyPathCache(keyPath)
if err == nil {
return privKey, nil
}
}
db := b.wallet.Database()
err = walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// If the account doesn't exist, then we may need to create it
// for the first time in order to derive the keys that we
// require. We skip this if we're using a remote signer in which
// case we _need_ to create all accounts when creating the
// wallet, so it must exist now.
if !b.wallet.Manager.WatchOnly() {
err = b.createAccountIfNotExists(
addrmgrNs, keyDesc.Family, scope,
)
if err != nil {
return err
}
}
// If the public key isn't set or they have a non-zero index,
// then we know that the caller instead knows the derivation
// path for a key.
if keyDesc.PubKey == nil || keyDesc.Index > 0 {
// Now that we know the account exists, we can safely
// derive the full private key from the given path.
path := waddrmgr.DerivationPath{
InternalAccount: uint32(keyDesc.Family),
Branch: 0,
Index: keyDesc.Index,
}
addr, err := scope.DeriveFromKeyPath(addrmgrNs, path)
if err != nil {
return err
}
key, err = addr.(waddrmgr.ManagedPubKeyAddress).PrivKey()
if err != nil {
return err
}
return nil
}
// If the public key isn't nil, then this indicates that we
// need to scan for the private key, assuming that we know the
// valid key family.
nextPath := waddrmgr.DerivationPath{
InternalAccount: uint32(keyDesc.Family),
Branch: 0,
Index: 0,
}
// We'll now iterate through our key range in an attempt to
// find the target public key.
//
// TODO(roasbeef): possibly move scanning into wallet to allow
// to be parallelized
for i := 0; i < MaxKeyRangeScan; i++ {
// Derive the next key in the range and fetch its
// managed address.
addr, err := scope.DeriveFromKeyPath(
addrmgrNs, nextPath,
)
if err != nil {
return err
}
managedAddr := addr.(waddrmgr.ManagedPubKeyAddress)
// If this is the target public key, then we'll return
// it directly back to the caller.
if managedAddr.PubKey().IsEqual(keyDesc.PubKey) {
key, err = managedAddr.PrivKey()
if err != nil {
return err
}
return nil
}
// This wasn't the target key, so roll forward and try
// the next one.
nextPath.Index++
}
// If we reach this point, then we we're unable to derive the
// private key, so return an error back to the user.
return ErrCannotDerivePrivKey
})
if err != nil {
return nil, err
}
return key, nil
}
// ECDH performs a scalar multiplication (ECDH-like operation) between the
// target key descriptor and remote public key. The output returned will be
// the sha256 of the resulting shared point serialized in compressed format. If
// k is our private key, and P is the public key, we perform the following
// operation:
//
// sx := k*P s := sha256(sx.SerializeCompressed())
//
// NOTE: This is part of the keychain.ECDHRing interface.
func (b *BtcWalletKeyRing) ECDH(keyDesc KeyDescriptor,
pub *btcec.PublicKey) ([32]byte, error) {
privKey, err := b.DerivePrivKey(keyDesc)
if err != nil {
return [32]byte{}, err
}
var (
pubJacobian btcec.JacobianPoint
s btcec.JacobianPoint
)
pub.AsJacobian(&pubJacobian)
btcec.ScalarMultNonConst(&privKey.Key, &pubJacobian, &s)
s.ToAffine()
sPubKey := btcec.NewPublicKey(&s.X, &s.Y)
h := sha256.Sum256(sPubKey.SerializeCompressed())
return h, nil
}
// SignMessage signs the given message, single or double SHA256 hashing it
// first, with the private key described in the key locator.
//
// NOTE: This is part of the keychain.MessageSignerRing interface.
func (b *BtcWalletKeyRing) SignMessage(keyLoc KeyLocator,
msg []byte, doubleHash bool) (*ecdsa.Signature, error) {
privKey, err := b.DerivePrivKey(KeyDescriptor{
KeyLocator: keyLoc,
})
if err != nil {
return nil, err
}
var digest []byte
if doubleHash {
digest = chainhash.DoubleHashB(msg)
} else {
digest = chainhash.HashB(msg)
}
return ecdsa.Sign(privKey, digest), nil
}
// SignMessageCompact signs the given message, single or double SHA256 hashing
// it first, with the private key described in the key locator and returns
// the signature in the compact, public key recoverable format.
//
// NOTE: This is part of the keychain.MessageSignerRing interface.
func (b *BtcWalletKeyRing) SignMessageCompact(keyLoc KeyLocator,
msg []byte, doubleHash bool) ([]byte, error) {
privKey, err := b.DerivePrivKey(KeyDescriptor{
KeyLocator: keyLoc,
})
if err != nil {
return nil, err
}
var digest []byte
if doubleHash {
digest = chainhash.DoubleHashB(msg)
} else {
digest = chainhash.HashB(msg)
}
return ecdsa.SignCompact(privKey, digest, true)
}
// SignMessageSchnorr uses the Schnorr signature algorithm to sign the given
// message, single or double SHA256 hashing it first, with the private key
// described in the key locator and the optional tweak applied to the private
// key.
//
// NOTE: This is part of the keychain.MessageSignerRing interface.
func (b *BtcWalletKeyRing) SignMessageSchnorr(keyLoc KeyLocator,
msg []byte, doubleHash bool, taprootTweak []byte,
tag []byte) (*schnorr.Signature, error) {
privKey, err := b.DerivePrivKey(KeyDescriptor{
KeyLocator: keyLoc,
})
if err != nil {
return nil, err
}
if len(taprootTweak) > 0 {
privKey = txscript.TweakTaprootPrivKey(*privKey, taprootTweak)
}
// If a tag was provided, we need to take the tagged hash of the input.
var digest []byte
switch {
case len(tag) > 0:
taggedHash := chainhash.TaggedHash(tag, msg)
digest = taggedHash[:]
case doubleHash:
digest = chainhash.DoubleHashB(msg)
default:
digest = chainhash.HashB(msg)
}
return schnorr.Sign(privKey, digest)
}