1 package waddrmgr
2 3 import (
4 "crypto/rand"
5 "crypto/sha512"
6 "fmt"
7 "github.com/p9c/p9/pkg/log"
8 "github.com/p9c/p9/pkg/btcaddr"
9 "github.com/p9c/p9/pkg/chaincfg"
10 "sync"
11 "time"
12 13 "github.com/p9c/p9/pkg/snacl"
14 "github.com/p9c/p9/pkg/util/hdkeychain"
15 "github.com/p9c/p9/pkg/util/zero"
16 "github.com/p9c/p9/pkg/walletdb"
17 )
18 19 const (
20 // MaxAccountNum is the maximum allowed account number. This value was chosen
21 // because accounts are hardened children and therefore must not exceed the
22 // hardened child range of extended keys and it provides a reserved account at
23 // the top of the range for supporting imported addresses.
24 MaxAccountNum = hdkeychain.HardenedKeyStart - 2 // 2^31 - 2
25 // MaxAddressesPerAccount is the maximum allowed number of addresses per account
26 // number. This value is based on the limitation of the underlying hierarchical
27 // deterministic key derivation.
28 MaxAddressesPerAccount = hdkeychain.HardenedKeyStart - 1
29 // ImportedAddrAccount is the account number to use for all imported addresses.
30 // This is useful since normal accounts are derived from the root hierarchical
31 // deterministic key and imported addresses do not fit into that model.
32 ImportedAddrAccount = MaxAccountNum + 1 // 2^31 - 1
33 // ImportedAddrAccountName is the name of the imported account.
34 ImportedAddrAccountName = "imported"
35 // DefaultAccountNum is the number of the default account.
36 DefaultAccountNum = 0
37 // defaultAccountName is the initial name of the default account. Note that the
38 // default account may be renamed and is not a reserved name, so the default
39 // account might not be named "default" and non-default accounts may be named
40 // "default".
41 //
42 // Account numbers never change, so the DefaultAccountNum should be used to
43 // refer to (and only to) the default account.
44 defaultAccountName = "default"
45 // The hierarchy described by BIP0043 is:
46 //
47 // m/<purpose>'/*
48 //
49 // This is further extended by BIP0044 to:
50 //
51 // m/44'/<coin type>'/<account>'/<branch>/<address index>
52 //
53 // The branch is 0 for external addresses and 1 for internal addresses.
54 // maxCoinType is the maximum allowed coin type used when structuring the
55 // BIP0044 multi-account hierarchy. This value is based on the limitation of the
56 // underlying hierarchical deterministic key derivation.
57 maxCoinType = hdkeychain.HardenedKeyStart - 1
58 // ExternalBranch is the child number to use when performing BIP0044 style
59 // hierarchical deterministic key derivation for the external branch.
60 ExternalBranch uint32 = 0
61 // InternalBranch is the child number to use when performing BIP0044 style
62 // hierarchical deterministic key derivation for the internal branch.
63 InternalBranch uint32 = 1
64 // saltSize is the number of bytes of the salt used when hashing private
65 // passphrases.
66 saltSize = 32
67 )
68 69 // isReservedAccountName returns true if the account name is reserved. Reserved
70 // accounts may never be renamed, and other accounts may not be renamed to a
71 // reserved name.
72 func isReservedAccountName(name string) bool {
73 return name == ImportedAddrAccountName
74 }
75 76 // isReservedAccountNum returns true if the account number is reserved. Reserved
77 // accounts may not be renamed.
78 func isReservedAccountNum(acct uint32) bool {
79 return acct == ImportedAddrAccount
80 }
81 82 // ScryptOptions is used to hold the scrypt parameters needed when deriving new
83 // passphrase keys.
84 type ScryptOptions struct {
85 N, R, P int
86 }
87 88 // OpenCallbacks houses caller-provided callbacks that may be called when
89 // opening an existing manager. The open blocks on the execution of these
90 // functions.
91 type OpenCallbacks struct {
92 // ObtainSeed is a callback function that is potentially invoked during
93 // upgrades. It is intended to be used to request the wallet seed from the user
94 // (or any other mechanism the caller deems fit).
95 ObtainSeed ObtainUserInputFunc
96 // ObtainPrivatePass is a callback function that is potentially invoked during
97 // upgrades. It is intended to be used to request the wallet private passphrase
98 // from the user (or any other mechanism the caller deems fit).
99 ObtainPrivatePass ObtainUserInputFunc
100 }
101 102 // DefaultScryptOptions is the default options used with scrypt.
103 var DefaultScryptOptions = ScryptOptions{
104 N: 262144, // 2^18
105 R: 8,
106 P: 1,
107 }
108 109 // addrKey is used to uniquely identify an address even when those addresses
110 // would end up being the same bitcoin address (as is the case for pay-to-pubkey
111 // and pay-to-pubkey-hash style of addresses).
112 type addrKey string
113 114 // accountInfo houses the current state of the internal and external branches of
115 // an account along with the extended keys needed to derive new keys. It also
116 // handles locking by keeping an encrypted version of the serialized private
117 // extended key so the unencrypted versions can be cleared from memory when the
118 // address manager is locked.
119 type accountInfo struct {
120 acctName string
121 // The account key is used to derive the branches which in turn derive the
122 // internal and external addresses. The accountKeyPriv will be nil when the
123 // address manager is locked.
124 acctKeyEncrypted []byte
125 acctKeyPriv *hdkeychain.ExtendedKey
126 acctKeyPub *hdkeychain.ExtendedKey
127 lastExternalAddr ManagedAddress
128 lastInternalAddr ManagedAddress
129 // The external branch is used for all addresses which are intended for external
130 // use.
131 nextExternalIndex uint32
132 // The internal branch is used for all adddresses which are only intended for
133 // internal wallet use such as change addresses.
134 nextInternalIndex uint32
135 }
136 137 // AccountProperties contains properties associated with each account, such as
138 // the account name, number, and the nubmer of derived and imported keys.
139 type AccountProperties struct {
140 AccountName string
141 AccountNumber uint32
142 ExternalKeyCount uint32
143 InternalKeyCount uint32
144 ImportedKeyCount uint32
145 }
146 147 // unlockDeriveInfo houses the information needed to derive a private key for a
148 // managed address when the address manager is unlocked. See the deriveOnUnlock
149 // field in the Manager struct for more details on how this is used.
150 type unlockDeriveInfo struct {
151 managedAddr ManagedAddress
152 branch uint32
153 index uint32
154 }
155 156 // SecretKeyGenerator is the function signature of a method that can generate
157 // secret keys for the address manager.
158 type SecretKeyGenerator func(
159 passphrase *[]byte, config *ScryptOptions,
160 ) (*snacl.SecretKey, error)
161 162 // defaultNewSecretKey returns a new secret key. See newSecretKey.
163 func defaultNewSecretKey(
164 passphrase *[]byte,
165 config *ScryptOptions,
166 ) (*snacl.SecretKey, error) {
167 return snacl.NewSecretKey(passphrase, config.N, config.R, config.P)
168 }
169 170 var (
171 // secretKeyGen is the inner method that is executed when calling newSecretKey.
172 secretKeyGen = defaultNewSecretKey
173 // secretKeyGenMtx protects access to secretKeyGen, so that it can be replaced
174 // in testing.
175 secretKeyGenMtx sync.RWMutex
176 )
177 178 // SetSecretKeyGen replaces the existing secret key generator, and returns the
179 // previous generator.
180 func SetSecretKeyGen(keyGen SecretKeyGenerator) SecretKeyGenerator {
181 secretKeyGenMtx.Lock()
182 oldKeyGen := secretKeyGen
183 secretKeyGen = keyGen
184 secretKeyGenMtx.Unlock()
185 return oldKeyGen
186 }
187 188 // newSecretKey generates a new secret key using the active secretKeyGen.
189 func newSecretKey(passphrase *[]byte, config *ScryptOptions) (*snacl.SecretKey, error) {
190 secretKeyGenMtx.RLock()
191 defer secretKeyGenMtx.RUnlock()
192 return secretKeyGen(passphrase, config)
193 }
194 195 // EncryptorDecryptor provides an abstraction on top of snacl.CryptoKey so that
196 // our tests can use dependency injection to force the behaviour they need.
197 type EncryptorDecryptor interface {
198 Encrypt(in []byte) ([]byte, error)
199 Decrypt(in []byte) ([]byte, error)
200 Bytes() []byte
201 CopyBytes([]byte)
202 Zero()
203 }
204 205 // cryptoKey extends snacl.CryptoKey to implement EncryptorDecryptor.
206 type cryptoKey struct {
207 snacl.CryptoKey
208 }
209 210 // Bytes returns a copy of this crypto key's byte slice.
211 func (ck *cryptoKey) Bytes() []byte {
212 return ck.CryptoKey[:]
213 }
214 215 // CopyBytes copies the bytes from the given slice into this CryptoKey.
216 func (ck *cryptoKey) CopyBytes(from []byte) {
217 copy(ck.CryptoKey[:], from)
218 }
219 220 // defaultNewCryptoKey returns a new CryptoKey. See newCryptoKey.
221 func defaultNewCryptoKey() (EncryptorDecryptor, error) {
222 var key *snacl.CryptoKey
223 var e error
224 if key, e = snacl.GenerateCryptoKey(); E.Chk(e) {
225 return nil, e
226 }
227 return &cryptoKey{*key}, nil
228 }
229 230 // CryptoKeyType is used to differentiate between different kinds of crypto
231 // keys.
232 type CryptoKeyType byte
233 234 // Crypto key types.
235 const (
236 // CKTPrivate specifies the key that is used for encryption of private key
237 // material such as derived extended private keys and imported private keys.
238 CKTPrivate CryptoKeyType = iota
239 // CKTScript specifies the key that is used for encryption of scripts.
240 CKTScript
241 // CKTPublic specifies the key that is used for encryption of public key
242 // material such as dervied extended public keys and imported public keys.
243 CKTPublic
244 )
245 246 // newCryptoKey is used as a way to replace the new crypto key generation
247 // function used so tests can provide a version that fails for testing error
248 // paths.
249 var newCryptoKey = defaultNewCryptoKey
250 251 // Manager represents a concurrency safe crypto currency address manager and key
252 // store.
253 type Manager struct {
254 mtx sync.RWMutex
255 // scopedManager is a mapping of scope of scoped manager, the manager itself
256 // loaded into memory.
257 scopedManagers map[KeyScope]*ScopedKeyManager
258 externalAddrSchemas map[AddressType][]KeyScope
259 internalAddrSchemas map[AddressType][]KeyScope
260 syncState syncState
261 birthday time.Time
262 chainParams *chaincfg.Params
263 // masterKeyPub is the secret key used to secure the cryptoKeyPub key and
264 // masterKeyPriv is the secret key used to secure the cryptoKeyPriv key. This
265 // approach is used because it makes changing the passwords much simpler as it
266 // then becomes just changing these keys. It also provides future flexibility.
267 //
268 // NOTE: This is not the same thing as BIP0032 master node extended key.
269 //
270 // The underlying master private key will be zeroed when the address manager is
271 // locked.
272 masterKeyPub *snacl.SecretKey
273 masterKeyPriv *snacl.SecretKey
274 // cryptoKeyPub is the key used to encrypt public extended keys and addresses.
275 cryptoKeyPub EncryptorDecryptor
276 // cryptoKeyPriv is the key used to encrypt private data such as the master
277 // hierarchical deterministic extended key.
278 //
279 // This key will be zeroed when the address manager is locked.
280 cryptoKeyPrivEncrypted []byte
281 cryptoKeyPriv EncryptorDecryptor
282 // cryptoKeyScript is the key used to encrypt script data.
283 //
284 // This key will be zeroed when the address manager is locked.
285 cryptoKeyScriptEncrypted []byte
286 cryptoKeyScript EncryptorDecryptor
287 // privPassphraseSalt and hashedPrivPassphrase allow for the secure detection of
288 // a correct passphrase on manager unlock when the manager is already unlocked.
289 // The hash is zeroed each lock.
290 privPassphraseSalt [saltSize]byte
291 hashedPrivPassphrase [sha512.Size]byte
292 watchingOnly bool
293 locked bool
294 closed bool
295 }
296 297 // WatchOnly returns true if the root manager is in watch only mode, and false otherwise.
298 func (m *Manager) WatchOnly() bool {
299 m.mtx.RLock()
300 defer m.mtx.RUnlock()
301 return m.watchingOnly
302 }
303 304 // lock performs a best try effort to remove and zero all secret keys associated
305 // with the address manager.
306 //
307 // This function MUST be called with the manager lock held for writes.
308 func (m *Manager) lock() {
309 for _, manager := range m.scopedManagers {
310 // Clear all of the account private keys.
311 for _, acctInfo := range manager.acctInfo {
312 if acctInfo.acctKeyPriv != nil {
313 acctInfo.acctKeyPriv.Zero()
314 }
315 acctInfo.acctKeyPriv = nil
316 }
317 }
318 // Remove clear text private keys and scripts from all address entries.
319 for _, manager := range m.scopedManagers {
320 for _, ma := range manager.addrs {
321 switch addr := ma.(type) {
322 case *managedAddress:
323 addr.lock()
324 case *scriptAddress:
325 addr.lock()
326 }
327 }
328 }
329 // Remove clear text private master and crypto keys from memory.
330 m.cryptoKeyScript.Zero()
331 m.cryptoKeyPriv.Zero()
332 m.masterKeyPriv.Zero()
333 // Zero the hashed passphrase.
334 zero.Bytea64(&m.hashedPrivPassphrase)
335 // NOTE: m.cryptoKeyPub is intentionally not cleared here as the address manager
336 // needs to be able to continue to read and decrypt public data which uses a
337 // separate derived key from the database even when it is locked.
338 m.locked = true
339 }
340 341 // Close cleanly shuts down the manager. It makes a best try effort to remove
342 // and zero all private key and sensitive public key material associated with
343 // the address manager from memory.
344 func (m *Manager) Close() {
345 m.mtx.Lock()
346 defer m.mtx.Unlock()
347 if m.closed {
348 return
349 }
350 for _, manager := range m.scopedManagers {
351 // Zero out the account keys (if any) of all sub key managers.
352 manager.Close()
353 }
354 // Attempt to clear private key material from memory.
355 if !m.watchingOnly && !m.locked {
356 m.lock()
357 }
358 // Remove clear text public master and crypto keys from memory.
359 m.cryptoKeyPub.Zero()
360 m.masterKeyPub.Zero()
361 m.closed = true
362 // return
363 }
364 365 // NewScopedKeyManager creates a new scoped key manager from the root manager. A
366 // scoped key manager is a sub-manager that only has the coin type key of a
367 // particular coin type and BIP0043 purpose. This is useful as it enables
368 // callers to create an arbitrary BIP0043 like schema with a stand alone
369 // manager.
370 //
371 // Note that a new scoped manager cannot be created if: the wallet is watch
372 // only, the manager hasn't been unlocked, or the root key has been. neutered
373 // from the database.
374 //
375 // TODO(roasbeef): addrtype of raw key means it'll look in scripts to possibly mark as gucci?
376 func (m *Manager) NewScopedKeyManager(
377 ns walletdb.ReadWriteBucket, scope KeyScope,
378 addrSchema ScopeAddrSchema,
379 ) (*ScopedKeyManager, error) {
380 m.mtx.Lock()
381 defer m.mtx.Unlock()
382 // If the manager is locked, then we can't create a new scoped manager.
383 if m.locked {
384 return nil, managerError(ErrLocked, errLocked, nil)
385 }
386 // Now that we know the manager is unlocked, we'll need to fetch the root master
387 // HD private key. This is required as we'll be attempting the following
388 // derivation: m/purpose'/cointype'
389 //
390 // Note that the path to the coin type is requires hardened derivation,
391 // therefore this can only be done if the wallet's root key hasn't been
392 // neutered.
393 var masterRootPrivEnc []byte
394 var e error
395 if masterRootPrivEnc, _, e = fetchMasterHDKeys(ns); E.Chk(e) {
396 return nil, e
397 }
398 // If the master root private key isn't found within the database, but we need
399 // to bail here as we can't create the cointype key without the master root
400 // private key.
401 if masterRootPrivEnc == nil {
402 return nil, managerError(ErrWatchingOnly, "", nil)
403 }
404 // Before we can derive any new scoped managers using this key, we'll need to
405 // fully decrypt it.
406 var serializedMasterRootPriv []byte
407 if serializedMasterRootPriv, e = m.cryptoKeyPriv.Decrypt(masterRootPrivEnc); E.Chk(e) {
408 str := fmt.Sprintf("failed to decrypt master root serialized private key")
409 return nil, managerError(ErrLocked, str, e)
410 }
411 // Now that we know the root priv is within the database, we'll decode it into a
412 // usable object.
413 var rootPriv *hdkeychain.ExtendedKey
414 if rootPriv, e = hdkeychain.NewKeyFromString(
415 string(serializedMasterRootPriv),
416 ); E.Chk(e) {
417 str := fmt.Sprintf("failed to create master extended private key")
418 zero.Bytes(serializedMasterRootPriv)
419 return nil, managerError(ErrKeyChain, str, e)
420 }
421 zero.Bytes(serializedMasterRootPriv)
422 // Now that we have the root private key, we'll fetch the scope bucket so we can
423 // create the proper internal name spaces.
424 scopeBucket := ns.NestedReadWriteBucket(scopeBucketName)
425 // Now that we know it's possible to actually create a new scoped manager, we'll
426 // carve out its bucket space within the database.
427 if e = createScopedManagerNS(scopeBucket, &scope); E.Chk(e) {
428 return nil, e
429 }
430 // With the database state created, we'll now write down the address schema of
431 // this particular scope type.
432 scopeSchemas := ns.NestedReadWriteBucket(scopeSchemaBucketName)
433 if scopeSchemas == nil {
434 str := "scope schema bucket not found"
435 return nil, managerError(ErrDatabase, str, nil)
436 }
437 scopeKey := scopeToBytes(&scope)
438 schemaBytes := scopeSchemaToBytes(&addrSchema)
439 if e = scopeSchemas.Put(scopeKey[:], schemaBytes); E.Chk(e) {
440 return nil, e
441 }
442 // With the database state created, we'll now derive the cointype key using the
443 // master HD private key, then encrypt it along with the first account using our
444 // crypto keys.
445 if e = createManagerKeyScope(
446 ns, scope, rootPriv, m.cryptoKeyPub, m.cryptoKeyPriv,
447 ); E.Chk(e) {
448 return nil, e
449 }
450 // Finally, we'll register this new scoped manager with the root manager.
451 m.scopedManagers[scope] = &ScopedKeyManager{
452 scope: scope,
453 addrSchema: addrSchema,
454 rootManager: m,
455 addrs: make(map[addrKey]ManagedAddress),
456 acctInfo: make(map[uint32]*accountInfo),
457 }
458 m.externalAddrSchemas[addrSchema.ExternalAddrType] = append(
459 m.externalAddrSchemas[addrSchema.ExternalAddrType], scope,
460 )
461 m.internalAddrSchemas[addrSchema.InternalAddrType] = append(
462 m.internalAddrSchemas[addrSchema.InternalAddrType], scope,
463 )
464 return m.scopedManagers[scope], nil
465 }
466 467 // FetchScopedKeyManager attempts to fetch an active scoped manager according to
468 // its registered scope. If the manger is found, then a nil error is returned
469 // along with the active scoped manager. Otherwise, a nil manager and a non-nil
470 // error will be returned.
471 func (m *Manager) FetchScopedKeyManager(scope KeyScope) (*ScopedKeyManager, error) {
472 m.mtx.RLock()
473 defer m.mtx.RUnlock()
474 sm, ok := m.scopedManagers[scope]
475 if !ok {
476 str := fmt.Sprintf("scope %v not found", scope)
477 return nil, managerError(ErrScopeNotFound, str, nil)
478 }
479 return sm, nil
480 }
481 482 // ActiveScopedKeyManagers returns a slice of all the active scoped key managers
483 // currently known by the root key manager.
484 func (m *Manager) ActiveScopedKeyManagers() []*ScopedKeyManager {
485 m.mtx.RLock()
486 defer m.mtx.RUnlock()
487 scopedManagers := make([]*ScopedKeyManager, len(m.scopedManagers))
488 for _, smgr := range m.scopedManagers {
489 scopedManagers = append(scopedManagers, smgr)
490 }
491 return scopedManagers
492 }
493 494 // ScopesForExternalAddrType returns the set of key scopes that are able to
495 // produce the target address type as external addresses.
496 func (m *Manager) ScopesForExternalAddrType(addrType AddressType) []KeyScope {
497 m.mtx.RLock()
498 defer m.mtx.RUnlock()
499 return m.externalAddrSchemas[addrType]
500 }
501 502 // ScopesForInternalAddrTypes returns the set of key scopes that are able to
503 // produce the target address type as internal addresses.
504 func (m *Manager) ScopesForInternalAddrTypes(addrType AddressType) []KeyScope {
505 m.mtx.RLock()
506 defer m.mtx.RUnlock()
507 return m.internalAddrSchemas[addrType]
508 }
509 510 // NeuterRootKey is a special method that should be used once a caller is
511 // *certain* that no further scoped managers are to be created. This method will
512 // *delete* the encrypted master HD root private key from the database.
513 func (m *Manager) NeuterRootKey(ns walletdb.ReadWriteBucket) (e error) {
514 m.mtx.Lock()
515 defer m.mtx.Unlock()
516 // First, we'll fetch the current master HD keys from the database.
517 var masterRootPrivEnc []byte
518 if masterRootPrivEnc, _, e = fetchMasterHDKeys(ns); E.Chk(e) {
519 return e
520 }
521 // If the root master private key is already nil, then we'll return a nil error
522 // here as the root key has already been permanently neutered.
523 if masterRootPrivEnc == nil {
524 return nil
525 }
526 zero.Bytes(masterRootPrivEnc)
527 // Otherwise, we'll neuter the root key permanently by deleting the encrypted
528 // master HD key from the database.
529 return ns.NestedReadWriteBucket(mainBucketName).Delete(masterHDPrivName)
530 }
531 532 // Address returns a managed address given the passed address if it is known to
533 // the address manager. A managed address differs from the passed address in
534 // that it also potentially contains extra information needed to sign
535 // transactions such as the associated private key for pay-to-pubkey and
536 // pay-to-pubkey-hash addresses and the script associated with
537 // pay-to-script-hash addresses.
538 func (m *Manager) Address(
539 ns walletdb.ReadBucket,
540 address btcaddr.Address,
541 ) (ManagedAddress, error) {
542 m.mtx.RLock()
543 defer m.mtx.RUnlock()
544 // We'll iterate through each of the known scoped managers, and see if any of them now of the target address.
545 for _, scopedMgr := range m.scopedManagers {
546 addr, e := scopedMgr.Address(ns, address)
547 if e != nil {
548 continue
549 }
550 return addr, nil
551 }
552 // If the address wasn't known to any of the scoped managers, then we'll return an error.
553 str := fmt.Sprintf("unable to find key for addr %v", address)
554 return nil, managerError(ErrAddressNotFound, str, nil)
555 }
556 557 // MarkUsed updates the used flag for the provided address.
558 func (m *Manager) MarkUsed(ns walletdb.ReadWriteBucket, address btcaddr.Address) (e error) {
559 m.mtx.RLock()
560 defer m.mtx.RUnlock()
561 // Run through all the known scoped managers, and attempt to mark the address as
562 // used for each one. First, we'll figure out which scoped manager this address
563 // belong to.
564 for _, scopedMgr := range m.scopedManagers {
565 if _, e = scopedMgr.Address(ns, address); E.Chk(e) {
566 continue
567 }
568 // We've found the manager that this address belongs to, so we can mark the
569 // address as used and return.
570 return scopedMgr.MarkUsed(ns, address)
571 }
572 // If we get to this point, then we weren't able to find the address in any of
573 // the managers, so we'll exit with an error.
574 str := fmt.Sprintf("unable to find key for addr %v", address)
575 return managerError(ErrAddressNotFound, str, nil)
576 }
577 578 // AddrAccount returns the account to which the given address belongs. We also
579 // return the scoped manager that owns the addr+account combo.
580 func (m *Manager) AddrAccount(
581 ns walletdb.ReadBucket,
582 address btcaddr.Address,
583 ) (*ScopedKeyManager, uint32, error) {
584 m.mtx.RLock()
585 defer m.mtx.RUnlock()
586 var e error
587 for _, scopedMgr := range m.scopedManagers {
588 if _, e = scopedMgr.Address(ns, address); e != nil /*T.Chk(e)*/ {
589 // D.Ln(address)
590 continue
591 }
592 // We've found the manager that this address belongs to, so we can retrieve the
593 // address' account along with the manager that the addr belongs to.
594 var accNo uint32
595 if accNo, e = scopedMgr.AddrAccount(ns, address); T.Chk(e) {
596 return nil, 0, e
597 }
598 return scopedMgr, accNo, e
599 }
600 // If we get to this point, then we weren't able to find the address in any of
601 // the managers, so we'll exit with an error.
602 str := fmt.Sprintf("unable to find key for addr %v", address)
603 return nil, 0, managerError(ErrAddressNotFound, str, nil)
604 }
605 606 // ForEachActiveAccountAddress calls the given function with each active address
607 // of the given account stored in the manager, across all active scopes,
608 // breaking early on error.
609 //
610 // TODO(tuxcanfly): actually return only active addresses
611 func (m *Manager) ForEachActiveAccountAddress(
612 ns walletdb.ReadBucket,
613 account uint32, fn func(maddr ManagedAddress) error,
614 ) (e error) {
615 m.mtx.RLock()
616 defer m.mtx.RUnlock()
617 for _, scopedMgr := range m.scopedManagers {
618 if e = scopedMgr.ForEachActiveAccountAddress(ns, account, fn); E.Chk(e) {
619 return e
620 }
621 }
622 return nil
623 }
624 625 // ForEachActiveAddress calls the given function with each active address stored
626 // in the manager, breaking early on error.
627 func (m *Manager) ForEachActiveAddress(ns walletdb.ReadBucket, fn func(addr btcaddr.Address) error) (e error) {
628 m.mtx.RLock()
629 defer m.mtx.RUnlock()
630 for _, scopedMgr := range m.scopedManagers {
631 if e = scopedMgr.ForEachActiveAddress(ns, fn); E.Chk(e) {
632 return e
633 }
634 }
635 return nil
636 }
637 638 // ForEachAccountAddress calls the given function with each address of the given
639 // account stored in the manager, breaking early on error.
640 func (m *Manager) ForEachAccountAddress(
641 ns walletdb.ReadBucket, account uint32,
642 fn func(maddr ManagedAddress) error,
643 ) (e error) {
644 m.mtx.RLock()
645 defer m.mtx.RUnlock()
646 for _, scopedMgr := range m.scopedManagers {
647 if e = scopedMgr.ForEachAccountAddress(ns, account, fn); E.Chk(e) {
648 return e
649 }
650 }
651 return nil
652 }
653 654 // ChainParams returns the chain parameters for this address manager.
655 func (m *Manager) ChainParams() *chaincfg.Params {
656 // NOTE: No need for mutex here since the net field does not change after the
657 // manager instance is created.
658 return m.chainParams
659 }
660 661 // ChangePassphrase changes either the public or private passphrase to the
662 // provided value depending on the private flag. In order to change the private
663 // password, the address manager must not be watching-only.
664 //
665 // The new passphrase keys are derived using the scrypt parameters in the
666 // options, so changing the passphrase may be used to bump the computational
667 // difficulty needed to brute force the passphrase.
668 func (m *Manager) ChangePassphrase(
669 ns walletdb.ReadWriteBucket, oldPassphrase,
670 newPassphrase []byte, private bool, config *ScryptOptions,
671 ) (e error) {
672 // No private passphrase to change for a watching-only address manager.
673 if private && m.watchingOnly {
674 return managerError(ErrWatchingOnly, errWatchingOnly, nil)
675 }
676 m.mtx.Lock()
677 defer m.mtx.Unlock()
678 // Ensure the provided old passphrase is correct. This check is done using a
679 // copy of the appropriate master key depending on the private flag to ensure
680 // the current state is not altered. The temp key is cleared when done to avoid
681 // leaving a copy in memory.
682 var keyName string
683 secretKey := snacl.SecretKey{Key: &snacl.CryptoKey{}}
684 if private {
685 keyName = "private"
686 secretKey.Parameters = m.masterKeyPriv.Parameters
687 } else {
688 keyName = "public"
689 secretKey.Parameters = m.masterKeyPub.Parameters
690 }
691 if e = secretKey.DeriveKey(&oldPassphrase); E.Chk(e) {
692 if e == snacl.ErrInvalidPassword {
693 str := fmt.Sprintf(
694 "invalid passphrase for %s master key", keyName,
695 )
696 return managerError(ErrWrongPassphrase, str, nil)
697 }
698 str := fmt.Sprintf("failed to derive %s master key", keyName)
699 return managerError(ErrCrypto, str, e)
700 }
701 defer secretKey.Zero()
702 // Generate a new master key from the passphrase which is used to secure the
703 // actual secret keys.
704 var newMasterKey *snacl.SecretKey
705 if newMasterKey, e = newSecretKey(&newPassphrase, config); E.Chk(e) {
706 str := "failed to create new master private key"
707 return managerError(ErrCrypto, str, e)
708 }
709 newKeyParams := newMasterKey.Marshal()
710 if private {
711 // Technically, the locked state could be checked here to only do the decrypts
712 // when the address manager is locked as the clear text keys are already
713 // available in memory when it is unlocked, but this is not a hot path,
714 // decryption is quite fast, and it's less cyclomatic complexity to simply
715 // decrypt in either case.
716 //
717 // Create a new salt that will be used for hashing the new passphrase each
718 // unlock.
719 var passphraseSalt [saltSize]byte
720 if _, e = rand.Read(passphraseSalt[:]); E.Chk(e) {
721 str := "failed to read random source for passhprase salt"
722 return managerError(ErrCrypto, str, e)
723 }
724 // Re-encrypt the crypto private key using the new master private key.
725 var decPriv []byte
726 if decPriv, e = secretKey.Decrypt(m.cryptoKeyPrivEncrypted); E.Chk(e) {
727 str := "failed to decrypt crypto private key"
728 return managerError(ErrCrypto, str, e)
729 }
730 var encPriv []byte
731 if encPriv, e = newMasterKey.Encrypt(decPriv); E.Chk(e) {
732 zero.Bytes(decPriv)
733 str := "failed to encrypt crypto private key"
734 return managerError(ErrCrypto, str, e)
735 }
736 zero.Bytes(decPriv)
737 // Re-encrypt the crypto script key using the new master private key.
738 var decScript []byte
739 if decScript, e = secretKey.Decrypt(m.cryptoKeyScriptEncrypted); E.Chk(e) {
740 str := "failed to decrypt crypto script key"
741 return managerError(ErrCrypto, str, e)
742 }
743 var encScript []byte
744 if encScript, e = newMasterKey.Encrypt(decScript); E.Chk(e) {
745 zero.Bytes(decScript)
746 str := "failed to encrypt crypto script key"
747 return managerError(ErrCrypto, str, e)
748 }
749 zero.Bytes(decScript)
750 // When the manager is locked, ensure the new clear text master key is cleared
751 // from memory now that it is no longer needed. If unlocked, create the new
752 // passphrase hash with the new passphrase and salt.
753 var hashedPassphrase [sha512.Size]byte
754 if m.locked {
755 newMasterKey.Zero()
756 } else {
757 saltedPassphrase := append(passphraseSalt[:], newPassphrase...)
758 hashedPassphrase = sha512.Sum512(saltedPassphrase)
759 zero.Bytes(saltedPassphrase)
760 }
761 // Save the new keys and netparams to the db in a single transaction.
762 if e = putCryptoKeys(ns, nil, encPriv, encScript); E.Chk(e) {
763 return maybeConvertDbError(e)
764 }
765 if e = putMasterKeyParams(ns, nil, newKeyParams); E.Chk(e) {
766 return maybeConvertDbError(e)
767 }
768 // Now that the db has been successfully updated, clear the old key and set the
769 // new one.
770 copy(m.cryptoKeyPrivEncrypted, encPriv)
771 copy(m.cryptoKeyScriptEncrypted, encScript)
772 m.masterKeyPriv.Zero() // Clear the old key.
773 m.masterKeyPriv = newMasterKey
774 m.privPassphraseSalt = passphraseSalt
775 m.hashedPrivPassphrase = hashedPassphrase
776 } else {
777 // Re-encrypt the crypto public key using the new master public key.
778 var encryptedPub []byte
779 if encryptedPub, e = newMasterKey.Encrypt(m.cryptoKeyPub.Bytes()); E.Chk(e) {
780 str := "failed to encrypt crypto public key"
781 return managerError(ErrCrypto, str, e)
782 }
783 // Save the new keys and netparams to the the db in a single
784 // transaction.
785 if e = putCryptoKeys(ns, encryptedPub, nil, nil); E.Chk(e) {
786 return maybeConvertDbError(e)
787 }
788 if e = putMasterKeyParams(ns, newKeyParams, nil); E.Chk(e) {
789 return maybeConvertDbError(e)
790 }
791 // Now that the db has been successfully updated, clear the old key and set the
792 // new one.
793 m.masterKeyPub.Zero()
794 m.masterKeyPub = newMasterKey
795 }
796 return nil
797 }
798 799 // ConvertToWatchingOnly converts the current address manager to a locked
800 // watching-only address manager.
801 //
802 // WARNING: This function removes private keys from the existing address manager
803 // which means they will no longer be available. Typically the caller will make
804 // a copy of the existing wallet database and modify the copy since otherwise it
805 // would mean permanent loss of any imported private keys and scripts.
806 //
807 // Executing this function on a manager that is already watching-only will have
808 // no effect.
809 func (m *Manager) ConvertToWatchingOnly(ns walletdb.ReadWriteBucket) (e error) {
810 m.mtx.Lock()
811 defer m.mtx.Unlock()
812 // Exit now if the manager is already watching-only.
813 if m.watchingOnly {
814 return nil
815 }
816 // Remove all private key material and mark the new database as watching only.
817 if e = deletePrivateKeys(ns); E.Chk(e) {
818 return maybeConvertDbError(e)
819 }
820 if e = putWatchingOnly(ns, true); E.Chk(e) {
821 return maybeConvertDbError(e)
822 }
823 // Lock the manager to remove all clear text private key material from memory if
824 // needed.
825 if !m.locked {
826 m.lock()
827 }
828 // This section clears and removes the encrypted private key material that is
829 // ordinarily used to unlock the manager. Since the the manager is being
830 // converted to watching-only, the encrypted private key material is no longer
831 // needed.
832 //
833 // Clear and remove all of the encrypted acount private keys.
834 for _, manager := range m.scopedManagers {
835 for _, acctInfo := range manager.acctInfo {
836 zero.Bytes(acctInfo.acctKeyEncrypted)
837 acctInfo.acctKeyEncrypted = nil
838 }
839 }
840 // Clear and remove encrypted private keys and encrypted scripts from all
841 // address entries.
842 for _, manager := range m.scopedManagers {
843 for _, ma := range manager.addrs {
844 switch addr := ma.(type) {
845 case *managedAddress:
846 zero.Bytes(addr.privKeyEncrypted)
847 addr.privKeyEncrypted = nil
848 case *scriptAddress:
849 zero.Bytes(addr.scriptEncrypted)
850 addr.scriptEncrypted = nil
851 }
852 }
853 }
854 // Clear and remove encrypted private and script crypto keys.
855 zero.Bytes(m.cryptoKeyScriptEncrypted)
856 m.cryptoKeyScriptEncrypted = nil
857 m.cryptoKeyScript = nil
858 zero.Bytes(m.cryptoKeyPrivEncrypted)
859 m.cryptoKeyPrivEncrypted = nil
860 m.cryptoKeyPriv = nil
861 // The master private key is derived from a passphrase when the manager is
862 // unlocked, so there is no encrypted version to zero. However, it is no longer
863 // needed, so nil it.
864 m.masterKeyPriv = nil
865 // Mark the manager watching-only.
866 m.watchingOnly = true
867 return nil
868 }
869 870 // IsLocked returns whether or not the address managed is locked. When it is
871 // unlocked, the decryption key needed to decrypt private keys used for signing
872 // is in memory.
873 func (m *Manager) IsLocked() bool {
874 m.mtx.RLock()
875 defer m.mtx.RUnlock()
876 return m.isLocked()
877 }
878 879 // isLocked is an internal method returning whether or not the address manager
880 // is locked via an unprotected read.
881 //
882 // NOTE: The caller *MUST* acquire the Manager's mutex before invocation to
883 // avoid data races.
884 func (m *Manager) isLocked() bool {
885 return m.locked
886 }
887 888 // Lock performs a best try effort to remove and zero all secret keys associated
889 // with the address manager.
890 //
891 // This function will return an error if invoked on a watching-only address
892 // manager.
893 func (m *Manager) Lock() (e error) {
894 // A watching-only address manager can't be locked.
895 if m.watchingOnly {
896 return managerError(ErrWatchingOnly, errWatchingOnly, nil)
897 }
898 m.mtx.Lock()
899 defer m.mtx.Unlock()
900 // DBError on attempt to lock an already locked manager.
901 if m.locked {
902 return managerError(ErrLocked, errLocked, nil)
903 }
904 m.lock()
905 return nil
906 }
907 908 // Unlock derives the master private key from the specified passphrase. An
909 // invalid passphrase will return an error. Otherwise, the derived secret key is
910 // stored in memory until the address manager is locked. Any failures that occur
911 // during this function will result in the address manager being locked, even if
912 // it was already unlocked prior to calling this function.
913 //
914 // This function will return an error if invoked on a watching-only address
915 // manager.
916 func (m *Manager) Unlock(ns walletdb.ReadBucket, passphrase []byte) (e error) {
917 // A watching-only address manager can't be unlocked.
918 if m.watchingOnly {
919 return managerError(ErrWatchingOnly, errWatchingOnly, nil)
920 }
921 m.mtx.Lock()
922 defer m.mtx.Unlock()
923 // Avoid actually unlocking if the manager is already unlocked
924 // and the passphrases match.
925 if !m.locked {
926 saltedPassphrase := append(
927 m.privPassphraseSalt[:],
928 passphrase...,
929 )
930 hashedPassphrase := sha512.Sum512(saltedPassphrase)
931 zero.Bytes(saltedPassphrase)
932 if hashedPassphrase != m.hashedPrivPassphrase {
933 m.lock()
934 str := "invalid passphrase for master private key"
935 return managerError(ErrWrongPassphrase, str, nil)
936 }
937 return nil
938 }
939 // Derive the master private key using the provided passphrase.
940 if e = m.masterKeyPriv.DeriveKey(&passphrase); E.Chk(e) {
941 m.lock()
942 if e == snacl.ErrInvalidPassword {
943 str := "invalid passphrase for master private key"
944 return managerError(ErrWrongPassphrase, str, nil)
945 }
946 str := "failed to derive master private key"
947 return managerError(ErrCrypto, str, e)
948 }
949 // Use the master private key to decrypt the crypto private key.
950 var decryptedKey []byte
951 if decryptedKey, e = m.masterKeyPriv.Decrypt(m.cryptoKeyPrivEncrypted); E.Chk(e) {
952 m.lock()
953 str := "failed to decrypt crypto private key"
954 return managerError(ErrCrypto, str, e)
955 }
956 m.cryptoKeyPriv.CopyBytes(decryptedKey)
957 zero.Bytes(decryptedKey)
958 // Use the crypto private key to decrypt all of the account private extended
959 // keys.
960 for _, manager := range m.scopedManagers {
961 var acctKeyPriv *hdkeychain.ExtendedKey
962 for account, acctInfo := range manager.acctInfo {
963 var decrypted []byte
964 if decrypted, e = m.cryptoKeyPriv.Decrypt(acctInfo.acctKeyEncrypted); E.Chk(e) {
965 m.lock()
966 str := fmt.Sprintf("failed to decrypt account %d private key", account)
967 return managerError(ErrCrypto, str, e)
968 }
969 if acctKeyPriv, e = hdkeychain.NewKeyFromString(string(decrypted)); E.Chk(e) {
970 zero.Bytes(decrypted)
971 m.lock()
972 str := fmt.Sprintf("failed to regenerate account %d extended key", account)
973 return managerError(ErrKeyChain, str, e)
974 }
975 zero.Bytes(decrypted)
976 acctInfo.acctKeyPriv = acctKeyPriv
977 }
978 // We'll also derive any private keys that are pending due to them being created
979 // while the address manager was locked.
980 for _, info := range manager.deriveOnUnlock {
981 var addressKey *hdkeychain.ExtendedKey
982 if addressKey, e = manager.deriveKeyFromPath(
983 ns, info.managedAddr.Account(), info.branch,
984 info.index, true,
985 ); E.Chk(e) {
986 m.lock()
987 return e
988 }
989 // It's ok to ignore the error here since it can only fail if the extended key
990 // is not private, however it was just derived as a private key.
991 privKey, _ := addressKey.ECPrivKey()
992 addressKey.Zero()
993 privKeyBytes := privKey.Serialize()
994 var privKeyEncrypted []byte
995 if privKeyEncrypted, e = m.cryptoKeyPriv.Encrypt(privKeyBytes); E.Chk(e) {
996 zero.BigInt(privKey.D)
997 m.lock()
998 str := fmt.Sprintf("failed to encrypt private key for address %s", info.managedAddr.Address())
999 return managerError(ErrCrypto, str, e)
1000 }
1001 zero.BigInt(privKey.D)
1002 switch a := info.managedAddr.(type) {
1003 case *managedAddress:
1004 a.privKeyEncrypted = privKeyEncrypted
1005 a.privKeyCT = privKeyBytes
1006 case *scriptAddress:
1007 }
1008 // Avoid re-deriving this key on subsequent unlocks.
1009 manager.deriveOnUnlock[0] = nil
1010 manager.deriveOnUnlock = manager.deriveOnUnlock[1:]
1011 }
1012 }
1013 m.locked = false
1014 saltedPassphrase := append(m.privPassphraseSalt[:], passphrase...)
1015 m.hashedPrivPassphrase = sha512.Sum512(saltedPassphrase)
1016 zero.Bytes(saltedPassphrase)
1017 return nil
1018 }
1019 1020 // ValidateAccountName validates the given account name and returns an error, if
1021 // any.
1022 func ValidateAccountName(name string) (e error) {
1023 if name == "" {
1024 str := "accounts may not be named the empty string"
1025 return managerError(ErrInvalidAccount, str, nil)
1026 }
1027 if isReservedAccountName(name) {
1028 str := "reserved account name"
1029 return managerError(ErrInvalidAccount, str, nil)
1030 }
1031 return nil
1032 }
1033 1034 // selectCryptoKey selects the appropriate crypto key based on the key type. An
1035 // error is returned when an invalid key type is specified or the requested key
1036 // requires the manager to be unlocked when it isn't.
1037 //
1038 // This function MUST be called with the manager lock held for reads.
1039 func (m *Manager) selectCryptoKey(keyType CryptoKeyType) (EncryptorDecryptor, error) {
1040 if keyType == CKTPrivate || keyType == CKTScript {
1041 // The manager must be unlocked to work with the private keys.
1042 if m.locked || m.watchingOnly {
1043 return nil, managerError(ErrLocked, errLocked, nil)
1044 }
1045 }
1046 var cryptoKey EncryptorDecryptor
1047 switch keyType {
1048 case CKTPrivate:
1049 cryptoKey = m.cryptoKeyPriv
1050 case CKTScript:
1051 cryptoKey = m.cryptoKeyScript
1052 case CKTPublic:
1053 cryptoKey = m.cryptoKeyPub
1054 default:
1055 return nil, managerError(
1056 ErrInvalidKeyType, "invalid key type",
1057 nil,
1058 )
1059 }
1060 return cryptoKey, nil
1061 }
1062 1063 // Encrypt in using the crypto key type specified by keyType.
1064 func (m *Manager) Encrypt(keyType CryptoKeyType, in []byte) ([]byte, error) {
1065 // Encryption must be performed under the manager mutex since the keys are
1066 // cleared when the manager is locked.
1067 m.mtx.Lock()
1068 defer m.mtx.Unlock()
1069 var e error
1070 var cryptoKey EncryptorDecryptor
1071 if cryptoKey, e = m.selectCryptoKey(keyType); E.Chk(e) {
1072 return nil, e
1073 }
1074 var encrypted []byte
1075 if encrypted, e = cryptoKey.Encrypt(in); E.Chk(e) {
1076 return nil, managerError(ErrCrypto, "failed to encrypt", e)
1077 }
1078 return encrypted, nil
1079 }
1080 1081 // Decrypt in using the crypto key type specified by keyType.
1082 func (m *Manager) Decrypt(keyType CryptoKeyType, in []byte) ([]byte, error) {
1083 // Decryption must be performed under the manager mutex since the keys are
1084 // cleared when the manager is locked.
1085 m.mtx.Lock()
1086 defer m.mtx.Unlock()
1087 var cryptoKey EncryptorDecryptor
1088 var e error
1089 if cryptoKey, e = m.selectCryptoKey(keyType); E.Chk(e) {
1090 return nil, e
1091 }
1092 var decrypted []byte
1093 if decrypted, e = cryptoKey.Decrypt(in); E.Chk(e) {
1094 return nil, managerError(ErrCrypto, "failed to decrypt", e)
1095 }
1096 return decrypted, nil
1097 }
1098 1099 // newManager returns a new locked address manager with the given parameters.
1100 func newManager(
1101 chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey,
1102 masterKeyPriv *snacl.SecretKey, cryptoKeyPub EncryptorDecryptor,
1103 cryptoKeyPrivEncrypted, cryptoKeyScriptEncrypted []byte, syncInfo *syncState,
1104 birthday time.Time, privPassphraseSalt [saltSize]byte,
1105 scopedManagers map[KeyScope]*ScopedKeyManager,
1106 ) *Manager {
1107 m := &Manager{
1108 chainParams: chainParams,
1109 syncState: *syncInfo,
1110 locked: true,
1111 birthday: birthday,
1112 masterKeyPub: masterKeyPub,
1113 masterKeyPriv: masterKeyPriv,
1114 cryptoKeyPub: cryptoKeyPub,
1115 cryptoKeyPrivEncrypted: cryptoKeyPrivEncrypted,
1116 cryptoKeyPriv: &cryptoKey{},
1117 cryptoKeyScriptEncrypted: cryptoKeyScriptEncrypted,
1118 cryptoKeyScript: &cryptoKey{},
1119 privPassphraseSalt: privPassphraseSalt,
1120 scopedManagers: scopedManagers,
1121 externalAddrSchemas: make(map[AddressType][]KeyScope),
1122 internalAddrSchemas: make(map[AddressType][]KeyScope),
1123 }
1124 for _, sMgr := range m.scopedManagers {
1125 externalType := sMgr.AddrSchema().ExternalAddrType
1126 internalType := sMgr.AddrSchema().InternalAddrType
1127 scope := sMgr.Scope()
1128 m.externalAddrSchemas[externalType] = append(
1129 m.externalAddrSchemas[externalType], scope,
1130 )
1131 m.internalAddrSchemas[internalType] = append(
1132 m.internalAddrSchemas[internalType], scope,
1133 )
1134 }
1135 return m
1136 }
1137 1138 // deriveCoinTypeKey derives the cointype key which can be used to derive the
1139 // extended key for an account according to the hierarchy described by BIP0044
1140 // given the coin type key.
1141 //
1142 // In particular this is the hierarchical deterministic extended key path:
1143 // m/purpose'/<coin type>'
1144 func deriveCoinTypeKey(
1145 masterNode *hdkeychain.ExtendedKey,
1146 scope KeyScope,
1147 ) (*hdkeychain.ExtendedKey, error) {
1148 // Enforce maximum coin type.
1149 var e error
1150 if scope.Coin > maxCoinType {
1151 e = managerError(ErrCoinTypeTooHigh, errCoinTypeTooHigh, nil)
1152 return nil, e
1153 }
1154 // The hierarchy described by BIP0043 is:
1155 //
1156 // m/<purpose>'/*
1157 //
1158 // This is further extended by BIP0044 to:
1159 //
1160 // m/44'/<coin type>'/<account>'/<branch>/<address index>
1161 //
1162 // However, as this is a generic key store for any family for BIP0044 standards,
1163 // we'll use the custom scope to govern our key derivation.
1164 //
1165 // The branch is 0 for external addresses and 1 for internal addresses. Derive
1166 // the purpose key as a child of the master node.
1167 var purpose *hdkeychain.ExtendedKey
1168 if purpose, e = masterNode.Child(scope.Purpose + hdkeychain.HardenedKeyStart); E.Chk(e) {
1169 return nil, e
1170 }
1171 // Derive the coin type key as a child of the purpose key.
1172 var coinTypeKey *hdkeychain.ExtendedKey
1173 if coinTypeKey, e = purpose.Child(scope.Coin + hdkeychain.HardenedKeyStart); E.Chk(e) {
1174 return nil, e
1175 }
1176 return coinTypeKey, nil
1177 }
1178 1179 // deriveAccountKey derives the extended key for an account according to the
1180 // hierarchy described by BIP0044 given the master node.
1181 //
1182 // In particular this is the hierarchical deterministic extended key path:
1183 //
1184 // m/purpose'/<coin type>'/<account>'
1185 func deriveAccountKey(coinTypeKey *hdkeychain.ExtendedKey, account uint32) (*hdkeychain.ExtendedKey, error) {
1186 // Enforce maximum account number.
1187 var er ManagerError
1188 if account > MaxAccountNum {
1189 er = managerError(ErrAccountNumTooHigh, errAcctTooHigh, nil)
1190 return nil, er
1191 }
1192 // Derive the account key as a child of the coin type key.
1193 return coinTypeKey.Child(account + hdkeychain.HardenedKeyStart)
1194 }
1195 1196 // checkBranchKeys ensures deriving the extended keys for the internal and
1197 // external branches given an account key does not result in an invalid child
1198 // error which means the chosen seed is not usable. This conforms to the
1199 // hierarchy described by the BIP0044 family so long as the account key is
1200 // already derived accordingly.
1201 //
1202 // In particular this is the hierarchical deterministic extended key path:
1203 //
1204 // m/purpose'/<coin type>'/<account>'/<branch>
1205 //
1206 // The branch is 0 for external addresses and 1 for internal addresses.
1207 func checkBranchKeys(acctKey *hdkeychain.ExtendedKey) (e error) {
1208 // Derive the external branch as the first child of the account key.
1209 if _, e = acctKey.Child(ExternalBranch); E.Chk(e) {
1210 return e
1211 }
1212 // Derive the external branch as the second child of the account key.
1213 if _, e = acctKey.Child(InternalBranch); E.Chk(e) {
1214 }
1215 return e
1216 }
1217 1218 // loadManager returns a new address manager that results from loading it from
1219 // the passed opened database. The public passphrase is required to decrypt the
1220 // public keys.
1221 func loadManager(
1222 ns walletdb.ReadBucket, pubPassphrase []byte,
1223 chainParams *chaincfg.Params,
1224 ) (*Manager, error) {
1225 D.Ln("loading address manager", log.Caller("from", 1))
1226 // Verify the version is neither too old or too new.
1227 var version uint32
1228 var e error
1229 D.Ln("fetching manager version")
1230 if version, e = fetchManagerVersion(ns); E.Chk(e) {
1231 str := "failed to fetch version for update"
1232 return nil, managerError(ErrDatabase, str, e)
1233 }
1234 if version < latestMgrVersion {
1235 str := "database upgrade required"
1236 D.Ln(str)
1237 return nil, managerError(ErrUpgrade, str, nil)
1238 } else if version > latestMgrVersion {
1239 str := "database version is greater than latest understood version"
1240 D.Ln(str)
1241 return nil, managerError(ErrUpgrade, str, nil)
1242 }
1243 // Load whether or not the manager is watching-only from the db.
1244 var watchingOnly bool
1245 D.Ln("loading watching only state from db")
1246 if watchingOnly, e = fetchWatchingOnly(ns); E.Chk(e) {
1247 return nil, maybeConvertDbError(e)
1248 }
1249 // Load the master key netparams from the db.
1250 var masterKeyPubParams []byte
1251 var masterKeyPrivParams []byte
1252 D.Ln("fetching master key params")
1253 if masterKeyPubParams, masterKeyPrivParams, e = fetchMasterKeyParams(ns); E.Chk(e) {
1254 return nil, maybeConvertDbError(e)
1255 }
1256 // Load the crypto keys from the db.
1257 var cryptoKeyPubEnc, cryptoKeyPrivEnc, cryptoKeyScriptEnc []byte
1258 D.Ln("loading crypto keys from wallet db")
1259 if cryptoKeyPubEnc, cryptoKeyPrivEnc, cryptoKeyScriptEnc, e = fetchCryptoKeys(ns); E.Chk(e) {
1260 return nil, maybeConvertDbError(e)
1261 }
1262 // Load the sync state from the db.
1263 var syncedTo *BlockStamp
1264 D.Ln("loading wallet sync state")
1265 if syncedTo, e = fetchSyncedTo(ns); E.Chk(e) {
1266 return nil, maybeConvertDbError(e)
1267 }
1268 var startBlock *BlockStamp
1269 D.Ln("fetching start block for wallet")
1270 if startBlock, e = fetchStartBlock(ns); E.Chk(e) {
1271 return nil, maybeConvertDbError(e)
1272 }
1273 var birthday time.Time
1274 D.Ln("fetching wallet birthday")
1275 if birthday, e = fetchBirthday(ns); E.Chk(e) {
1276 return nil, maybeConvertDbError(e)
1277 }
1278 // When not a watching-only manager, set the master private key netparams, but
1279 // don't derive it now since the manager starts off locked.
1280 var masterKeyPriv snacl.SecretKey
1281 if !watchingOnly {
1282 D.Ln("unmarshalling wallet master private key parameters")
1283 if e = masterKeyPriv.Unmarshal(masterKeyPrivParams); E.Chk(e) {
1284 str := "failed to unmarshal master private key"
1285 return nil, managerError(ErrCrypto, str, e)
1286 }
1287 }
1288 // Derive the master public key using the serialized netparams and provided
1289 // passphrase.
1290 var masterKeyPub snacl.SecretKey
1291 D.Ln("unmarshalling wallet master public key")
1292 if e = masterKeyPub.Unmarshal(masterKeyPubParams); E.Chk(e) {
1293 str := "failed to unmarshal master public key"
1294 return nil, managerError(ErrCrypto, str, e)
1295 }
1296 D.F("deriving pub key passphrase key '%s'" , string(pubPassphrase))
1297 if e = masterKeyPub.DeriveKey(&pubPassphrase); E.Chk(e) {
1298 str := "invalid passphrase for master public key"
1299 return nil, managerError(ErrWrongPassphrase, str, nil)
1300 }
1301 // Use the master public key to decrypt the crypto public key.
1302 cryptoKeyPub := &cryptoKey{snacl.CryptoKey{}}
1303 var cryptoKeyPubCT []byte
1304 D.Ln("decrypting master public key")
1305 if cryptoKeyPubCT, e = masterKeyPub.Decrypt(cryptoKeyPubEnc); E.Chk(e) {
1306 str := "failed to decrypt crypto public key"
1307 return nil, managerError(ErrCrypto, str, e)
1308 }
1309 cryptoKeyPub.CopyBytes(cryptoKeyPubCT)
1310 zero.Bytes(cryptoKeyPubCT)
1311 // Create the sync state struct.
1312 D.Ln("creating new sync state")
1313 syncInfo := newSyncState(startBlock, syncedTo)
1314 // Generate private passphrase salt.
1315 var privPassphraseSalt [saltSize]byte
1316 D.Ln("generating private passphrase salt")
1317 if _, e = rand.Read(privPassphraseSalt[:]); E.Chk(e) {
1318 str := "failed to read random source for passphrase salt"
1319 return nil, managerError(ErrCrypto, str, e)
1320 }
1321 // Next, we'll need to load all known manager scopes from disk. Each scope is on
1322 // a distinct top-level path within our HD key chain.
1323 D.Ln("loading all known wallet address manager scopes")
1324 scopedManagers := make(map[KeyScope]*ScopedKeyManager)
1325 if e = forEachKeyScope(
1326 ns, func(scope KeyScope) (e error) {
1327 scopeSchema, e := fetchScopeAddrSchema(ns, &scope)
1328 if e != nil {
1329 return e
1330 }
1331 scopedManagers[scope] = &ScopedKeyManager{
1332 scope: scope,
1333 addrSchema: *scopeSchema,
1334 addrs: make(map[addrKey]ManagedAddress),
1335 acctInfo: make(map[uint32]*accountInfo),
1336 }
1337 return nil
1338 },
1339 ); E.Chk(e) {
1340 return nil, e
1341 }
1342 // Create new address manager with the given parameters. Also, override the
1343 // defaults for the additional fields which are not specified in the call to new
1344 // with the values loaded from the database.
1345 D.Ln("creating new wallet address manager")
1346 mgr := newManager(
1347 chainParams, &masterKeyPub, &masterKeyPriv,
1348 cryptoKeyPub, cryptoKeyPrivEnc, cryptoKeyScriptEnc, syncInfo,
1349 birthday, privPassphraseSalt, scopedManagers,
1350 )
1351 mgr.watchingOnly = watchingOnly
1352 for _, scopedManager := range scopedManagers {
1353 scopedManager.rootManager = mgr
1354 }
1355 D.Ln("successfully created new wallet address manager")
1356 return mgr, nil
1357 }
1358 1359 // Open loads an existing address manager from the given namespace. The public
1360 // passphrase is required to decrypt the public keys used to protect the public
1361 // information such as addresses. This is important since access to BIP0032
1362 // extended keys means it is possible to generate all future addresses.
1363 //
1364 // If a config structure is passed to the function, that configuration will
1365 // override the defaults.
1366 //
1367 // A ManagerError with an error code of ErrNoExist will be returned if the
1368 // passed manager does not exist in the specified namespace.
1369 func Open(
1370 ns walletdb.ReadBucket, pubPassphrase []byte,
1371 chainParams *chaincfg.Params,
1372 ) (*Manager, error) {
1373 D.Ln("opening address manager")
1374 // Return an error if the manager has NOT already been created in the
1375 // given database namespace.
1376 exists := managerExists(ns)
1377 if !exists {
1378 str := "the specified address manager does not exist"
1379 return nil, managerError(ErrNoExist, str, nil)
1380 }
1381 return loadManager(ns, pubPassphrase, chainParams)
1382 }
1383 1384 // DoUpgrades performs any necessary upgrades to the address manager contained
1385 // in the wallet database, namespaced by the top level bucket key namespaceKey.
1386 func DoUpgrades(
1387 db walletdb.DB, namespaceKey []byte, pubPassphrase []byte,
1388 chainParams *chaincfg.Params, cbs *OpenCallbacks,
1389 ) (e error) {
1390 return upgradeManager(db, namespaceKey, pubPassphrase, chainParams, cbs)
1391 }
1392 1393 // createManagerKeyScope creates a new key scoped for a target manager's scope.
1394 // This partitions key derivation for a particular purpose+coin tuple, allowing
1395 // multiple address derivation schemes to be maintained concurrently.
1396 func createManagerKeyScope(
1397 ns walletdb.ReadWriteBucket,
1398 scope KeyScope, root *hdkeychain.ExtendedKey,
1399 cryptoKeyPub, cryptoKeyPriv EncryptorDecryptor,
1400 ) (e error) {
1401 // Derive the cointype key according to the passed scope.
1402 var coinTypeKeyPriv *hdkeychain.ExtendedKey
1403 if coinTypeKeyPriv, e = deriveCoinTypeKey(root, scope); E.Chk(e) {
1404 str := "failed to derive cointype extended key"
1405 return managerError(ErrKeyChain, str, e)
1406 }
1407 defer coinTypeKeyPriv.Zero()
1408 // Derive the account key for the first account according our BIP0044-like
1409 // derivation.
1410 var acctKeyPriv *hdkeychain.ExtendedKey
1411 if acctKeyPriv, e = deriveAccountKey(coinTypeKeyPriv, 0); E.Chk(e) {
1412 // The seed is unusable if the any of the children in the required hierarchy
1413 // can't be derived due to invalid child.
1414 if e == hdkeychain.ErrInvalidChild {
1415 str := "the provided seed is unusable"
1416 return managerError(
1417 ErrKeyChain, str,
1418 hdkeychain.ErrUnusableSeed,
1419 )
1420 }
1421 return e
1422 }
1423 // Ensure the branch keys can be derived for the provided seed according to our
1424 // BIP0044-like derivation.
1425 if e = checkBranchKeys(acctKeyPriv); E.Chk(e) {
1426 // The seed is unusable if the any of the children in the required hierarchy
1427 // can't be derived due to invalid child.
1428 if e == hdkeychain.ErrInvalidChild {
1429 str := "the provided seed is unusable"
1430 return managerError(
1431 ErrKeyChain, str,
1432 hdkeychain.ErrUnusableSeed,
1433 )
1434 }
1435 return e
1436 }
1437 // The address manager needs the public extended key for the account.
1438 var acctKeyPub *hdkeychain.ExtendedKey
1439 if acctKeyPub, e = acctKeyPriv.Neuter(); E.Chk(e) {
1440 str := "failed to convert private key for account 0"
1441 return managerError(ErrKeyChain, str, e)
1442 }
1443 // Encrypt the cointype keys with the associated crypto keys.
1444 var coinTypeKeyPub *hdkeychain.ExtendedKey
1445 if coinTypeKeyPub, e = coinTypeKeyPriv.Neuter(); E.Chk(e) {
1446 str := "failed to convert cointype private key"
1447 return managerError(ErrKeyChain, str, e)
1448 }
1449 var coinTypePubEnc []byte
1450 if coinTypePubEnc, e = cryptoKeyPub.Encrypt([]byte(coinTypeKeyPub.String())); E.Chk(e) {
1451 str := "failed to encrypt cointype public key"
1452 return managerError(ErrCrypto, str, e)
1453 }
1454 var coinTypePrivEnc []byte
1455 if coinTypePrivEnc, e = cryptoKeyPriv.Encrypt([]byte(coinTypeKeyPriv.String())); E.Chk(e) {
1456 str := "failed to encrypt cointype private key"
1457 return managerError(ErrCrypto, str, e)
1458 }
1459 // Encrypt the default account keys with the associated crypto keys.
1460 var acctPubEnc []byte
1461 if acctPubEnc, e = cryptoKeyPub.Encrypt([]byte(acctKeyPub.String())); E.Chk(e) {
1462 str := "failed to encrypt public key for account 0"
1463 return managerError(ErrCrypto, str, e)
1464 }
1465 var acctPrivEnc []byte
1466 if acctPrivEnc, e = cryptoKeyPriv.Encrypt([]byte(acctKeyPriv.String())); E.Chk(e) {
1467 str := "failed to encrypt private key for account 0"
1468 return managerError(ErrCrypto, str, e)
1469 }
1470 // Save the encrypted cointype keys to the database.
1471 if e = putCoinTypeKeys(ns, &scope, coinTypePubEnc, coinTypePrivEnc); E.Chk(e) {
1472 return e
1473 }
1474 // Save the information for the default account to the database.
1475 if e = putAccountInfo(
1476 ns, &scope, DefaultAccountNum, acctPubEnc, acctPrivEnc, 0, 0,
1477 defaultAccountName,
1478 ); E.Chk(e) {
1479 return e
1480 }
1481 return putAccountInfo(
1482 ns, &scope, ImportedAddrAccount, nil, nil, 0, 0,
1483 ImportedAddrAccountName,
1484 )
1485 }
1486 1487 // Create creates a new address manager in the given namespace. The seed must
1488 // conform to the standards described in hdkeychain.NewMaster and will be used
1489 // to create the master root node from which all hierarchical deterministic
1490 // addresses are derived. This allows all chained addresses in the address
1491 // manager to be recovered by using the same seed.
1492 //
1493 // All private and public keys and information are protected by secret keys
1494 // derived from the provided private and public passphrases. The public
1495 // passphrase is required on subsequent opens of the address manager, and the
1496 // private passphrase is required to unlock the address manager in order to gain
1497 // access to any private keys and information.
1498 //
1499 // If a config structure is passed to the function, that configuration will
1500 // override the defaults.
1501 //
1502 // A ManagerError with an error code of ErrAlreadyExists will be returned the
1503 // address manager already exists in the specified namespace.
1504 func Create(
1505 ns walletdb.ReadWriteBucket, seed, pubPassphrase, privPassphrase []byte,
1506 chainParams *chaincfg.Params, config *ScryptOptions,
1507 birthday time.Time,
1508 ) (e error) {
1509 // Return an error if the manager has already been created in the given database
1510 // namespace.
1511 exists := managerExists(ns)
1512 if exists {
1513 return managerError(ErrAlreadyExists, errAlreadyExists, nil)
1514 }
1515 // Ensure the private passphrase is not empty.
1516 if len(privPassphrase) == 0 {
1517 str := "private passphrase may not be empty"
1518 return managerError(ErrEmptyPassphrase, str, nil)
1519 }
1520 // Perform the initial bucket creation and database namespace setup.
1521 if e = createManagerNS(ns, ScopeAddrMap); E.Chk(e) {
1522 return maybeConvertDbError(e)
1523 }
1524 if config == nil {
1525 config = &DefaultScryptOptions
1526 }
1527 // Generate new master keys. These master keys are used to protect the crypto
1528 // keys that will be generated next.
1529 var masterKeyPub *snacl.SecretKey
1530 if masterKeyPub, e = newSecretKey(&pubPassphrase, config); E.Chk(e) {
1531 str := "failed to master public key"
1532 return managerError(ErrCrypto, str, e)
1533 }
1534 var masterKeyPriv *snacl.SecretKey
1535 if masterKeyPriv, e = newSecretKey(&privPassphrase, config); E.Chk(e) {
1536 str := "failed to master private key"
1537 return managerError(ErrCrypto, str, e)
1538 }
1539 defer masterKeyPriv.Zero()
1540 // Generate the private passphrase salt. This is used when hashing passwords to
1541 // detect whether an unlock can be avoided when the manager is already unlocked.
1542 var privPassphraseSalt [saltSize]byte
1543 if _, e = rand.Read(privPassphraseSalt[:]); E.Chk(e) {
1544 str := "failed to read random source for passphrase salt"
1545 return managerError(ErrCrypto, str, e)
1546 }
1547 // Generate new crypto public, private, and script keys. These keys are used to
1548 // protect the actual public and private data such as addresses, extended keys,
1549 // and scripts.
1550 var cryptoKeyPub EncryptorDecryptor
1551 if cryptoKeyPub, e = newCryptoKey(); E.Chk(e) {
1552 str := "failed to generate crypto public key"
1553 return managerError(ErrCrypto, str, e)
1554 }
1555 var cryptoKeyPriv EncryptorDecryptor
1556 if cryptoKeyPriv, e = newCryptoKey(); E.Chk(e) {
1557 str := "failed to generate crypto private key"
1558 return managerError(ErrCrypto, str, e)
1559 }
1560 defer cryptoKeyPriv.Zero()
1561 var cryptoKeyScript EncryptorDecryptor
1562 if cryptoKeyScript, e = newCryptoKey(); E.Chk(e) {
1563 str := "failed to generate crypto script key"
1564 return managerError(ErrCrypto, str, e)
1565 }
1566 defer cryptoKeyScript.Zero()
1567 // Encrypt the crypto keys with the associated master keys.
1568 var cryptoKeyPubEnc []byte
1569 if cryptoKeyPubEnc, e = masterKeyPub.Encrypt(cryptoKeyPub.Bytes()); E.Chk(e) {
1570 str := "failed to encrypt crypto public key"
1571 return managerError(ErrCrypto, str, e)
1572 }
1573 var cryptoKeyPrivEnc []byte
1574 if cryptoKeyPrivEnc, e = masterKeyPriv.Encrypt(cryptoKeyPriv.Bytes()); E.Chk(e) {
1575 str := "failed to encrypt crypto private key"
1576 return managerError(ErrCrypto, str, e)
1577 }
1578 var cryptoKeyScriptEnc []byte
1579 if cryptoKeyScriptEnc, e = masterKeyPriv.Encrypt(cryptoKeyScript.Bytes()); E.Chk(e) {
1580 str := "failed to encrypt crypto script key"
1581 return managerError(ErrCrypto, str, e)
1582 }
1583 // Use the genesis block for the passed chain as the created at block for the
1584 // default.
1585 createdAt := &BlockStamp{Hash: *chainParams.GenesisHash, Height: 0}
1586 // Create the initial sync state.
1587 syncInfo := newSyncState(createdAt, createdAt)
1588 // Save the master key netparams to the database.
1589 pubParams := masterKeyPub.Marshal()
1590 privParams := masterKeyPriv.Marshal()
1591 if e = putMasterKeyParams(ns, pubParams, privParams); E.Chk(e) {
1592 return maybeConvertDbError(e)
1593 }
1594 // Generate the BIP0044 HD key structure to ensure the provided seed can
1595 // generate the required structure with no issues. Derive the master extended
1596 // key from the seed.
1597 var rootKey *hdkeychain.ExtendedKey
1598 if rootKey, e = hdkeychain.NewMaster(seed, chainParams); E.Chk(e) {
1599 str := "failed to derive master extended key"
1600 return managerError(ErrKeyChain, str, e)
1601 }
1602 var rootPubKey *hdkeychain.ExtendedKey
1603 if rootPubKey, e = rootKey.Neuter(); E.Chk(e) {
1604 str := "failed to neuter master extended key"
1605 return managerError(ErrKeyChain, str, e)
1606 }
1607 // Next, for each registers default manager scope, we'll create the hardened
1608 // cointype key for it, as well as the first default account.
1609 for _, defaultScope := range DefaultKeyScopes {
1610 if e = createManagerKeyScope(
1611 ns, defaultScope, rootKey, cryptoKeyPub, cryptoKeyPriv,
1612 ); E.Chk(e) {
1613 return maybeConvertDbError(e)
1614 }
1615 }
1616 // Before we proceed, we'll also store the root master private key within the
1617 // database in an encrypted format. This is required as in the future, we may
1618 // need to create additional scoped key managers.
1619 var masterHDPrivKeyEnc []byte
1620 if masterHDPrivKeyEnc, e = cryptoKeyPriv.Encrypt([]byte(rootKey.String())); E.Chk(e) {
1621 return maybeConvertDbError(e)
1622 }
1623 var masterHDPubKeyEnc []byte
1624 if masterHDPubKeyEnc, e = cryptoKeyPub.Encrypt([]byte(rootPubKey.String())); E.Chk(e) {
1625 return maybeConvertDbError(e)
1626 }
1627 if e = putMasterHDKeys(ns, masterHDPrivKeyEnc, masterHDPubKeyEnc); E.Chk(e) {
1628 return maybeConvertDbError(e)
1629 }
1630 // Save the encrypted crypto keys to the database.
1631 if e = putCryptoKeys(
1632 ns, cryptoKeyPubEnc, cryptoKeyPrivEnc,
1633 cryptoKeyScriptEnc,
1634 ); E.Chk(e) {
1635 return maybeConvertDbError(e)
1636 }
1637 // Save the fact this is not a watching-only address manager to the database.
1638 if e = putWatchingOnly(ns, false); E.Chk(e) {
1639 return maybeConvertDbError(e)
1640 }
1641 // Save the initial synced to state.
1642 if e = putSyncedTo(ns, &syncInfo.syncedTo); E.Chk(e) {
1643 return maybeConvertDbError(e)
1644 }
1645 if e = putStartBlock(ns, &syncInfo.startBlock); E.Chk(e) {
1646 return maybeConvertDbError(e)
1647 }
1648 // Use 48 hours as margin of safety for wallet birthday.
1649 return putBirthday(ns, birthday.Add(-48*time.Hour))
1650 }
1651