decred.org/dcrwallet/v3@v3.1.0/wallet/udb/addressmanager.go (about) 1 // Copyright (c) 2014-2016 The btcsuite developers 2 // Copyright (c) 2015-2019 The Decred developers 3 // Use of this source code is governed by an ISC 4 // license that can be found in the LICENSE file. 5 6 package udb 7 8 import ( 9 "crypto/rand" 10 "crypto/subtle" 11 "fmt" 12 "hash" 13 "io" 14 "sync" 15 16 "decred.org/dcrwallet/v3/errors" 17 "decred.org/dcrwallet/v3/internal/compat" 18 "decred.org/dcrwallet/v3/kdf" 19 "decred.org/dcrwallet/v3/wallet/internal/snacl" 20 "decred.org/dcrwallet/v3/wallet/walletdb" 21 "github.com/decred/dcrd/chaincfg/v3" 22 "github.com/decred/dcrd/dcrec/secp256k1/v4" 23 "github.com/decred/dcrd/dcrutil/v4" 24 "github.com/decred/dcrd/hdkeychain/v3" 25 "github.com/decred/dcrd/txscript/v4/stdaddr" 26 "github.com/decred/dcrd/wire" 27 "golang.org/x/crypto/blake2b" 28 "golang.org/x/crypto/chacha20poly1305" 29 ) 30 31 const ( 32 // MaxAccountNum is the maximum allowed account number. This value was 33 // chosen because accounts are hardened children and therefore must 34 // not exceed the hardened child range of extended keys and it provides 35 // a reserved account at the top of the range for supporting imported 36 // addresses. 37 MaxAccountNum = hdkeychain.HardenedKeyStart - 2 // 2^31 - 2 38 39 // MaxAddressesPerAccount is the maximum allowed number of addresses 40 // per account number. This value is based on the limitation of 41 // the underlying hierarchical deterministic key derivation. 42 MaxAddressesPerAccount = hdkeychain.HardenedKeyStart - 1 43 44 // ImportedAddrAccount is the account number to use for all imported 45 // addresses. This is useful since normal accounts are derived from the 46 // root hierarchical deterministic key and imported addresses do not 47 // fit into that model. 48 ImportedAddrAccount = MaxAccountNum + 1 // 2^31 - 1 49 50 // ImportedAddrAccountName is the name of the imported account. 51 ImportedAddrAccountName = "imported" 52 53 // DefaultAccountNum is the number of the default account. 54 DefaultAccountNum = 0 55 56 // defaultAccountName is the initial name of the default account. Note 57 // that the default account may be renamed and is not a reserved name, 58 // so the default account might not be named "default" and non-default 59 // accounts may be named "default". 60 // 61 // Account numbers never change, so the DefaultAccountNum should be used 62 // to refer to (and only to) the default account. 63 defaultAccountName = "default" 64 65 // The hierarchy described by BIP0043 is: 66 // m/<purpose>'/* 67 // This is further extended by BIP0044 to: 68 // m/44'/<coin type>'/<account>'/<branch>/<address index> 69 // 70 // The branch is 0 for external addresses and 1 for internal addresses. 71 72 // maxCoinType is the maximum allowed coin type used when structuring 73 // the BIP0044 multi-account hierarchy. This value is based on the 74 // limitation of the underlying hierarchical deterministic key 75 // derivation. 76 maxCoinType = hdkeychain.HardenedKeyStart - 1 77 78 // ExternalBranch is the child number to use when performing BIP0044 79 // style hierarchical deterministic key derivation for the external 80 // branch. 81 ExternalBranch uint32 = 0 82 83 // InternalBranch is the child number to use when performing BIP0044 84 // style hierarchical deterministic key derivation for the internal 85 // branch. 86 InternalBranch uint32 = 1 87 ) 88 89 // isReservedAccountName returns true if the account name is reserved. Reserved 90 // accounts may never be renamed, and other accounts may not be renamed to a 91 // reserved name. 92 func isReservedAccountName(name string) bool { 93 return name == ImportedAddrAccountName 94 } 95 96 // isReservedAccountNum returns true if the account number is reserved. 97 // Reserved accounts may not be renamed. 98 func isReservedAccountNum(acct uint32) bool { 99 return acct == ImportedAddrAccount 100 } 101 102 // normalizeAddress normalizes addresses for usage by the address manager. In 103 // particular, it converts all pubkeys to pubkey hash addresses so they are 104 // interchangeable by callers. 105 func normalizeAddress(addr stdaddr.Address) stdaddr.Address { 106 // Return public key hash for public keys. 107 if addr, ok := addr.(stdaddr.AddressPubKeyHasher); ok { 108 return addr.AddressPubKeyHash() 109 } 110 return addr 111 } 112 113 // scryptOptions is used to hold the scrypt parameters needed when deriving new 114 // passphrase keys. 115 type scryptOptions struct { 116 N, R, P int 117 } 118 119 // scryptOptionsForNet returns the desired scrypt options for a given network. 120 func scryptOptionsForNet(net wire.CurrencyNet) *scryptOptions { 121 if net == wire.SimNet { 122 return &scryptOptions{N: 2, R: 1, P: 1} 123 } 124 125 return &scryptOptions{ 126 N: 262144, // 2^18 127 R: 8, 128 P: 1, 129 } 130 } 131 132 // accountInfo houses the current state of the internal and external branches 133 // of an account along with the extended keys needed to derive new keys. It 134 // also handles locking by keeping an encrypted version of the serialized 135 // private extended key so the unencrypted versions can be cleared from memory 136 // when the address manager is locked. 137 type accountInfo struct { 138 acctName string 139 acctType accountType 140 141 // The account key is used to derive the branches which in turn derive 142 // the internal and external addresses. 143 // The accountKeyPriv will be nil when the address manager is locked, 144 // or the account is uniquely encrypted and not currently unlocked. 145 // acctKeyEncrypted is the encrypted account key, sealed using snacl 146 // when the account is protected by the wallet global passphrase, 147 // and sealed using XChaCha20Poly1305 with an Argon2id-derived key 148 // when uniquely encrypted separate from the global passphrase. 149 acctKeyEncrypted []byte 150 acctKeyPriv *hdkeychain.ExtendedKey 151 acctKeyPub *hdkeychain.ExtendedKey 152 uniqueKey *kdf.Argon2idParams 153 uniquePassHasher hash.Hash // blake2b-256 keyed hash with random bytes 154 uniquePassHash []byte 155 } 156 157 func argon2idKey(password []byte, k *kdf.Argon2idParams) keyType { 158 return keyType(kdf.DeriveKey(password, k, 32)) 159 } 160 161 const ( 162 xchacha20NonceSize = 24 163 poly1305TagSize = 16 164 xchacha20poly1305Overhead = xchacha20NonceSize + poly1305TagSize 165 ) 166 167 // improves type safety for seal and unseal funcs with a new type for 168 // argon2id-derived keys. 169 type keyType []byte 170 171 func seal(rand io.Reader, key keyType, plaintext []byte) ([]byte, error) { 172 sealedLen := len(plaintext) + xchacha20poly1305Overhead 173 nonce := make([]byte, xchacha20NonceSize, sealedLen) 174 _, err := io.ReadFull(rand, nonce) 175 if err != nil { 176 return nil, errors.E(errors.IO, err) 177 } 178 179 aead, err := chacha20poly1305.NewX(key) 180 if err != nil { 181 // wrong key len; this is always a programming mistake 182 // (bad type conversion to keyType). 183 panic(err) 184 } 185 sealed := aead.Seal(nonce, nonce, plaintext, nil) 186 return sealed, nil 187 } 188 189 func unseal(key keyType, ciphertext []byte) ([]byte, error) { 190 aead, err := chacha20poly1305.NewX(key) 191 if err != nil { 192 // wrong key len; this is always a programming mistake 193 // (bad type conversion to keyType). 194 panic(err) 195 } 196 if len(ciphertext) < xchacha20poly1305Overhead { 197 e := errors.Errorf("ciphertext too short (len %d) "+ 198 "to encode nonce and MAC tag", len(ciphertext)) 199 return nil, errors.E(errors.Crypto, e) 200 } 201 nonce := ciphertext[:xchacha20NonceSize] 202 ciphertext = ciphertext[xchacha20NonceSize:] 203 plaintext, err := aead.Open(nil, nonce, ciphertext, nil) 204 if err != nil { 205 // technically the ciphertext may have been tampered with, but 206 // to improve UX we report authentication failures as incorrect 207 // passphrases. 208 return nil, errors.E(errors.Passphrase) 209 } 210 return plaintext, nil 211 } 212 213 // AccountProperties contains properties associated with each account, such as 214 // the account name, number, and the nubmer of derived and imported keys. If no 215 // address usage has been recorded on any of the external or internal branches, 216 // the child index is ^uint32(0). 217 type AccountProperties = struct { 218 AccountNumber uint32 219 AccountName string 220 AccountType uint8 221 LastUsedExternalIndex uint32 222 LastUsedInternalIndex uint32 223 LastReturnedExternalIndex uint32 224 LastReturnedInternalIndex uint32 225 ImportedKeyCount uint32 226 AccountEncrypted bool 227 AccountUnlocked bool 228 } 229 230 // IsImportedVoting compares a uint8 to the internal importedVoting type and 231 // returns if the value represents an imported voting account. 232 func IsImportedVoting(acctType uint8) bool { 233 return acctType == uint8(importedVoting) 234 } 235 236 // defaultNewSecretKey returns a new secret key. See newSecretKey. 237 func defaultNewSecretKey(passphrase *[]byte, config *scryptOptions) (*snacl.SecretKey, error) { 238 return snacl.NewSecretKey(passphrase, config.N, config.R, config.P) 239 } 240 241 // newSecretKey is used as a way to replace the new secret key generation 242 // function used so tests can provide a version that fails for testing error 243 // paths. 244 var newSecretKey = defaultNewSecretKey 245 246 // EncryptorDecryptor provides an abstraction on top of snacl.CryptoKey so that 247 // our tests can use dependency injection to force the behaviour they need. 248 type EncryptorDecryptor interface { 249 Encrypt(in []byte) ([]byte, error) 250 Decrypt(in []byte) ([]byte, error) 251 Bytes() []byte 252 CopyBytes([]byte) 253 Zero() 254 } 255 256 // cryptoKey extends snacl.CryptoKey to implement EncryptorDecryptor. 257 type cryptoKey struct { 258 snacl.CryptoKey 259 } 260 261 // Bytes returns a copy of this crypto key's byte slice. 262 func (ck *cryptoKey) Bytes() []byte { 263 return ck.CryptoKey[:] 264 } 265 266 // CopyBytes copies the bytes from the given slice into this CryptoKey. 267 func (ck *cryptoKey) CopyBytes(from []byte) { 268 copy(ck.CryptoKey[:], from) 269 } 270 271 // defaultNewCryptoKey returns a new CryptoKey. See newCryptoKey. 272 func defaultNewCryptoKey() (EncryptorDecryptor, error) { 273 key, err := snacl.GenerateCryptoKey() 274 if err != nil { 275 return nil, err 276 } 277 return &cryptoKey{*key}, nil 278 } 279 280 // CryptoKeyType is used to differentiate between different kinds of 281 // crypto keys. 282 type CryptoKeyType byte 283 284 // Crypto key types. 285 const ( 286 // CKTPrivate specifies the key that is used for encryption of private 287 // key material such as derived extended private keys and imported 288 // private keys. 289 CKTPrivate CryptoKeyType = iota 290 291 _ // Was CKTScript, now removed. Left for iota to work properly. 292 293 // CKTPublic specifies the key that is used for encryption of public 294 // key material such as dervied extended public keys and imported public 295 // keys. 296 CKTPublic 297 ) 298 299 // newCryptoKey is used as a way to replace the new crypto key generation 300 // function used so tests can provide a version that fails for testing error 301 // paths. 302 var newCryptoKey = defaultNewCryptoKey 303 304 // Manager represents a concurrency safe crypto currency address manager and 305 // key store. 306 type Manager struct { 307 mtx sync.RWMutex 308 309 chainParams *chaincfg.Params 310 watchingOnly bool 311 locked bool 312 closed bool 313 314 // acctInfo houses information about accounts including what is needed 315 // to generate deterministic chained keys for each created account. 316 acctInfo map[uint32]*accountInfo 317 318 // masterKeyPub is the secret key used to secure the cryptoKeyPub key 319 // and masterKeyPriv is the secret key used to secure the cryptoKeyPriv 320 // key. This approach is used because it makes changing the passwords 321 // much simpler as it then becomes just changing these keys. It also 322 // provides future flexibility. 323 // 324 // NOTE: This is not the same thing as BIP0032 master node extended 325 // key. 326 // 327 // The underlying master private key will be zeroed when the address 328 // manager is locked. 329 masterKeyPub *snacl.SecretKey 330 masterKeyPriv *snacl.SecretKey 331 332 // cryptoKeyPub is the key used to encrypt public extended keys and 333 // addresses. 334 cryptoKeyPub EncryptorDecryptor 335 336 // cryptoKeyPriv is the key used to encrypt private data such as the 337 // master hierarchical deterministic extended key. 338 // 339 // This key will be zeroed when the address manager is locked. 340 cryptoKeyPrivEncrypted []byte 341 cryptoKeyPriv EncryptorDecryptor 342 343 // privPassphraseHasher is a blake2b-256 hasher (keyed with random 344 // bytes) to hash passphrases, to compare for correct passphrases when 345 // unlocking an already unlocked wallet without deriving another key. 346 privPassphraseHasher hash.Hash 347 privPassphraseHasherMu sync.Mutex // protects privPassphraseHasher 348 privPassphraseHash []byte // protected by m.mtx, not privPassphraseHasherMu 349 } 350 351 func zero(b []byte) { 352 for i := range b { 353 b[i] = 0 354 } 355 } 356 357 // lock performs a best try effort to remove and zero all secret keys associated 358 // with the address manager. 359 // 360 // This function MUST be called with the manager lock held for writes. 361 func (m *Manager) lock() { 362 // Clear all of the account private keys. 363 for _, acctInfo := range m.acctInfo { 364 if acctInfo.acctKeyPriv != nil { 365 acctInfo.acctKeyPriv.Zero() 366 } 367 acctInfo.acctKeyPriv = nil 368 } 369 370 // Remove clear text private master and crypto keys from memory. 371 m.cryptoKeyPriv.Zero() 372 m.masterKeyPriv.Zero() 373 374 // NOTE: m.cryptoKeyPub is intentionally not cleared here as the address 375 // manager needs to be able to continue to read and decrypt public data 376 // which uses a separate derived key from the database even when it is 377 // locked. 378 379 m.locked = true 380 m.privPassphraseHash = nil 381 } 382 383 // zeroSensitivePublicData performs a best try effort to remove and zero all 384 // sensitive public data associated with the address manager such as 385 // hierarchical deterministic extended public keys and the crypto public keys. 386 func (m *Manager) zeroSensitivePublicData() { 387 // Clear all of the account private keys. 388 for _, acctInfo := range m.acctInfo { 389 acctInfo.acctKeyPub.Zero() 390 acctInfo.acctKeyPub = nil 391 } 392 393 // Remove clear text public master and crypto keys from memory. 394 m.cryptoKeyPub.Zero() 395 m.masterKeyPub.Zero() 396 } 397 398 // WatchingOnly returns whether or not the wallet is in watching only mode. 399 func (m *Manager) WatchingOnly() bool { 400 return m.watchingOnly 401 } 402 403 // Close cleanly shuts down the manager. It makes a best try effort to remove 404 // and zero all private key and sensitive public key material associated with 405 // the address manager from memory. 406 func (m *Manager) Close() error { 407 m.mtx.Lock() 408 defer m.mtx.Unlock() 409 410 // Attempt to clear private key material from memory. 411 if !m.watchingOnly && !m.locked { 412 m.lock() 413 } 414 415 // Attempt to clear sensitive public key material from memory too. 416 m.zeroSensitivePublicData() 417 418 m.closed = true 419 return nil 420 } 421 422 // keyToManaged returns a new managed address for a public key and its BIP0044 423 // derivation path from the coin type key. 424 // 425 // This function MUST be called with the manager lock held for writes. 426 func (m *Manager) keyToManaged(pubKey []byte, account, branch, index uint32) (ManagedAddress, error) { 427 ma, err := newManagedAddressWithoutPrivKey(m, account, pubKey) 428 if err != nil { 429 return nil, err 430 } 431 if branch == InternalBranch { 432 ma.internal = true 433 } 434 435 ma.index = index 436 437 return ma, nil 438 } 439 440 // deriveKey returns either a public or private derived extended key based on 441 // the private flag for the given an account info, branch, and index. 442 func deriveKey(acctInfo *accountInfo, branch, index uint32, private bool) (*hdkeychain.ExtendedKey, error) { 443 // Choose the public or private extended key based on whether or not 444 // the private flag was specified. This, in turn, allows for public or 445 // private child derivation. 446 acctKey := acctInfo.acctKeyPub 447 if private { 448 if acctInfo.acctKeyPriv == nil { 449 if acctInfo.uniqueKey != nil { 450 return nil, errors.E(errors.Locked, 451 "account with unique passphrase is locked") 452 } 453 if len(acctInfo.acctKeyEncrypted) != 0 { 454 return nil, errors.E(errors.Locked, 455 "private key %s/%d/%d is locked", 456 acctInfo.acctName, branch, index) 457 } 458 return nil, errors.Errorf("no private key for %s/%d/%d", 459 acctInfo.acctName, branch, index) 460 } 461 acctKey = acctInfo.acctKeyPriv 462 } 463 464 // Derive and return the key. 465 branchKey, err := acctKey.Child(branch) 466 if err != nil { 467 return nil, err 468 } 469 addressKey, err := branchKey.Child(index) 470 branchKey.Zero() // Zero branch key after it's used. 471 return addressKey, err 472 } 473 474 // loadAccountInfo attempts to load and cache information about the given 475 // account from the database. This includes what is necessary to derive new 476 // keys for it and track the state of the internal and external branches. 477 // 478 // This function MUST be called with the manager lock held for writes. 479 func (m *Manager) loadAccountInfo(ns walletdb.ReadBucket, account uint32) (*accountInfo, error) { 480 // Return the account info from cache if it's available. 481 if acctInfo, ok := m.acctInfo[account]; ok { 482 return acctInfo, nil 483 } 484 485 // The account is either invalid or just wasn't cached, so attempt to 486 // load the information from the database. 487 row, err := fetchDBAccount(ns, account, DBVersion) 488 if err != nil { 489 return nil, err 490 } 491 492 // Create the new account info with the known information. The rest 493 // of the fields are filled out below. 494 acctInfo := new(accountInfo) 495 496 switch row := row.(type) { 497 case *dbBIP0044Account: 498 // Use the crypto public key to decrypt the account public extended key. 499 serializedKeyPub, err := m.cryptoKeyPub.Decrypt(row.pubKeyEncrypted) 500 if err != nil { 501 err := errors.Errorf("decrypt account %d pubkey: %v", account, err) 502 return nil, errors.E(errors.Crypto, err) 503 } 504 acctKeyPub, err := hdkeychain.NewKeyFromString(string(serializedKeyPub), m.chainParams) 505 if err != nil { 506 return nil, errors.E(errors.IO, err) 507 } 508 509 acctInfo.acctName = row.name 510 acctInfo.acctType = row.accountType() 511 acctInfo.acctKeyEncrypted = row.privKeyEncrypted 512 acctInfo.acctKeyPub = acctKeyPub 513 acctInfo.uniqueKey = row.uniqueKey 514 if acctInfo.uniqueKey != nil { // a passphrase hasher is required 515 hashKey := make([]byte, 32) 516 _, err = io.ReadFull(rand.Reader, hashKey) 517 if err != nil { 518 return nil, errors.E(errors.IO, err) 519 } 520 hasher, err := blake2b.New256(hashKey) 521 if err != nil { 522 return nil, errors.E(errors.IO, err) 523 } 524 acctInfo.uniquePassHasher = hasher 525 } 526 default: 527 return nil, errors.Errorf("unknown account type %T", row) 528 } 529 530 if !m.locked && len(acctInfo.acctKeyEncrypted) != 0 && acctInfo.uniqueKey == nil { 531 // Use the crypto private key to decrypt the account private 532 // extended keys. 533 decrypted, err := m.cryptoKeyPriv.Decrypt(acctInfo.acctKeyEncrypted) 534 if err != nil { 535 return nil, errors.E(errors.Crypto, errors.Errorf("decrypt account %d privkey: %v", account, err)) 536 } 537 538 acctKeyPriv, err := hdkeychain.NewKeyFromString(string(decrypted), m.chainParams) 539 if err != nil { 540 return nil, errors.E(errors.IO, err) 541 } 542 acctInfo.acctKeyPriv = acctKeyPriv 543 } 544 545 // Add it to the cache and return it when everything is successful. 546 m.acctInfo[account] = acctInfo 547 return acctInfo, nil 548 } 549 550 // AccountProperties returns properties associated with the account, such as the 551 // account number, name, and the number of derived and imported keys. 552 // 553 // TODO: Instead of opening a second read transaction after making a change, and 554 // then fetching the account properties with a new read tx, this can be made 555 // more performant by simply returning the new account properties during the 556 // change. 557 func (m *Manager) AccountProperties(ns walletdb.ReadBucket, account uint32) (*AccountProperties, error) { 558 defer m.mtx.RUnlock() 559 m.mtx.RLock() 560 561 props := &AccountProperties{AccountNumber: account} 562 563 // Until keys can be imported into any account, special handling is 564 // required for the imported account. 565 // 566 // loadAccountInfo errors when using it on the imported account since 567 // the accountInfo struct is filled with a BIP0044 account's extended 568 // keys, and the imported accounts has none. 569 // 570 // Since only the imported account allows imports currently, the number 571 // of imported keys for any other account is zero, and since the 572 // imported account cannot contain non-imported keys, the external and 573 // internal key counts for it are zero. 574 if account != ImportedAddrAccount { 575 acctInfo, err := m.loadAccountInfo(ns, account) 576 if err != nil { 577 return nil, err 578 } 579 props.AccountName, props.AccountType = acctInfo.acctName, uint8(acctInfo.acctType) 580 a, err := fetchDBAccount(ns, account, DBVersion) 581 if err != nil { 582 return nil, errors.E(errors.IO, err) 583 } 584 switch a := a.(type) { 585 case *dbBIP0044Account: 586 props.LastUsedExternalIndex = a.lastUsedExternalIndex 587 props.LastUsedInternalIndex = a.lastUsedInternalIndex 588 props.LastReturnedExternalIndex = a.lastReturnedExternalIndex 589 props.LastReturnedInternalIndex = a.lastReturnedInternalIndex 590 default: 591 return nil, errors.Errorf("unknown account type %T", a) 592 } 593 } else { 594 props.AccountName = ImportedAddrAccountName // reserved, nonchangable 595 596 // Could be more efficient if this was tracked by the db. 597 var importedKeyCount uint32 598 count := func(interface{}) error { 599 importedKeyCount++ 600 return nil 601 } 602 err := forEachAccountAddress(ns, ImportedAddrAccount, count) 603 if err != nil { 604 return nil, err 605 } 606 props.ImportedKeyCount = importedKeyCount 607 } 608 609 props.AccountEncrypted, props.AccountUnlocked = m.accountHasPassphrase(ns, account) 610 611 return props, nil 612 } 613 614 // AccountExtendedPubKey returns the extended public key for an account, which 615 // can then be used to derive BIP0044 branch keys. 616 func (m *Manager) AccountExtendedPubKey(dbtx walletdb.ReadTx, account uint32) (*hdkeychain.ExtendedKey, error) { 617 ns := dbtx.ReadBucket(waddrmgrBucketKey) 618 if account == ImportedAddrAccount { 619 return nil, errors.E(errors.Invalid, "imported account has no extended pubkey") 620 } 621 m.mtx.Lock() 622 acctInfo, err := m.loadAccountInfo(ns, account) 623 m.mtx.Unlock() 624 if err != nil { 625 return nil, err 626 } 627 if acctInfo.acctKeyPub == nil && account > ImportedAddrAccount { 628 return nil, errors.E(errors.Invalid, "hardened account xpub usage is forbidden") 629 } 630 return acctInfo.acctKeyPub, nil 631 } 632 633 // AccountExtendedPrivKey returns the extended private key for the given 634 // account. The account must already exist and the address manager must be 635 // unlocked for this operation to complete. 636 func (m *Manager) AccountExtendedPrivKey(dbtx walletdb.ReadTx, account uint32) (*hdkeychain.ExtendedKey, error) { 637 if account == ImportedAddrAccount { 638 return nil, errors.E(errors.Invalid, "imported address account has no extended privkey") 639 } 640 641 ns := dbtx.ReadBucket(waddrmgrBucketKey) 642 643 defer m.mtx.Unlock() 644 m.mtx.Lock() 645 646 acctInfo, err := m.loadAccountInfo(ns, account) 647 if err != nil { 648 return nil, err 649 } 650 if acctInfo.acctKeyPriv == nil && account > ImportedAddrAccount { 651 return nil, errors.E(errors.Invalid, "imported xpub account has no extended privkey") 652 } 653 if acctInfo.acctKeyPriv == nil { 654 return nil, errors.E(errors.Locked, "unable to access account extended privkey") 655 } 656 657 return acctInfo.acctKeyPriv, nil 658 } 659 660 // AccountBranchExtendedPubKey returns the extended public key of an account's 661 // branch, which then can be used to derive addresses belonging to the account. 662 func (m *Manager) AccountBranchExtendedPubKey(dbtx walletdb.ReadTx, account, branch uint32) (*hdkeychain.ExtendedKey, error) { 663 acctXpub, err := m.AccountExtendedPubKey(dbtx, account) 664 if err != nil { 665 return nil, err 666 } 667 return acctXpub.Child(branch) 668 } 669 670 // CoinTypePrivKey returns the coin type private key at the BIP0044 path 671 // m/44'/<coin type>' (coin type child indexes differ by the network). The key 672 // and all derived private keys should be cleared by the caller when finished. 673 // This method requires the wallet to be unlocked. 674 func (m *Manager) CoinTypePrivKey(dbtx walletdb.ReadTx) (*hdkeychain.ExtendedKey, error) { 675 defer m.mtx.RUnlock() 676 m.mtx.RLock() 677 678 if m.locked { 679 return nil, errors.E(errors.Locked) 680 } 681 if m.watchingOnly { 682 return nil, errors.E(errors.WatchingOnly) 683 } 684 685 ns := dbtx.ReadBucket(waddrmgrBucketKey) 686 687 _, coinTypePrivEnc, err := fetchCoinTypeKeys(ns) 688 if err != nil { 689 return nil, err 690 } 691 serializedKeyPriv, err := m.cryptoKeyPriv.Decrypt(coinTypePrivEnc) 692 if err != nil { 693 return nil, errors.E(errors.Crypto, errors.Errorf("decrypt cointype privkey: %v", err)) 694 } 695 coinTypeKeyPriv, err := hdkeychain.NewKeyFromString(string(serializedKeyPriv), m.chainParams) 696 zero(serializedKeyPriv) 697 if err != nil { 698 return nil, errors.E(errors.IO, err) 699 } 700 return coinTypeKeyPriv, nil 701 } 702 703 // CoinType returns the BIP0044 coin type currently in use. Early versions of 704 // the wallet used coin types that conflicted with other coins, preventing use 705 // of the same seed in multicurrency wallets. New (not restored) wallets are 706 // now created using the coin types assigned to Decred in SLIP0044: 707 // 708 // https://github.com/satoshilabs/slips/blob/master/slip-0044.md 709 // 710 // The address manager should be upgraded to the SLIP0044 coin type if it is 711 // currently using the legacy coin type and there are no used accounts or 712 // addresses. This procedure must be performed for seed restored wallets which 713 // save both coin types and, for backwards compatibility reasons, default to the 714 // legacy coin type. Both coin types for a network may be queried using the 715 // CoinTypes func and upgrades are performed using the UpgradeToSLIP0044CoinType 716 // method. 717 // 718 // Watching-only wallets that are created using an account xpub do not save the 719 // coin type keys and this method will return an error with code 720 // WatchingOnly on these wallets. 721 func (m *Manager) CoinType(dbtx walletdb.ReadTx) (uint32, error) { 722 ns := dbtx.ReadBucket(waddrmgrBucketKey) 723 mainBucket := ns.NestedReadBucket(mainBucketName) 724 725 legacyCoinType, slip0044CoinType := CoinTypes(m.chainParams) 726 727 if mainBucket.Get(coinTypeLegacyPubKeyName) != nil { 728 return legacyCoinType, nil 729 } 730 if mainBucket.Get(coinTypeSLIP0044PubKeyName) != nil { 731 return slip0044CoinType, nil 732 } 733 734 return 0, errors.E(errors.WatchingOnly, "watching wallets do not record coin type keys") 735 } 736 737 // UpgradeToSLIP0044CoinType upgrades a wallet from using the legacy coin type 738 // to the coin type registered to Decred as per SLIP0044. On mainnet, this 739 // upgrades the coin type from 20 to 42. On testnet and simnet, the coin type 740 // is upgraded to 1. This upgrade is only possible if the SLIP0044 coin type 741 // private key is saved and there is no address use for keys derived by the 742 // legacy coin type. 743 func (m *Manager) UpgradeToSLIP0044CoinType(dbtx walletdb.ReadWriteTx) error { 744 coinType, err := m.CoinType(dbtx) 745 if err != nil { 746 return err 747 } 748 legacyCoinType, _ := CoinTypes(m.chainParams) 749 if coinType != legacyCoinType { 750 return errors.E(errors.Invalid, "SLIP0044 coin type upgrade only possible on legacy coin type wallets") 751 } 752 753 ns := dbtx.ReadWriteBucket(waddrmgrBucketKey) 754 mainBucket := ns.NestedReadWriteBucket(mainBucketName) 755 756 coinTypeSLIP0044PubKeyEnc := mainBucket.Get(coinTypeSLIP0044PubKeyName) 757 coinTypeSLIP0044PrivKeyEnc := mainBucket.Get(coinTypeSLIP0044PrivKeyName) 758 if coinTypeSLIP0044PubKeyEnc == nil || coinTypeSLIP0044PrivKeyEnc == nil { 759 return errors.E(errors.Invalid, "missing keys for SLIP0044 coin type upgrade") 760 } 761 762 // Refuse to upgrade the coin type if any accounts or addresses have been 763 // used or derived. 764 lastAcct, err := m.LastAccount(ns) 765 if err != nil { 766 return err 767 } 768 acctProps, err := m.AccountProperties(ns, lastAcct) 769 if err != nil { 770 return err 771 } 772 if lastAcct != 0 || acctProps.LastReturnedExternalIndex != ^uint32(0) || 773 acctProps.LastReturnedInternalIndex != ^uint32(0) { 774 return errors.E(errors.Invalid, "wallets with returned addresses may not be upgraded to SLIP0044 coin type") 775 } 776 777 // Delete the legacy coin type keys. With these missing, the SLIP0044 coin 778 // type keys (which have already been checked to exist) will be used 779 // instead. 780 err = mainBucket.Delete(coinTypeLegacyPubKeyName) 781 if err != nil { 782 return errors.E(errors.IO, err) 783 } 784 err = mainBucket.Delete(coinTypeLegacyPrivKeyName) 785 if err != nil { 786 return errors.E(errors.IO, err) 787 } 788 789 // Rewrite the account 0 row using the SLIP0044 coin type key derivations. 790 serializedRow := mainBucket.Get(slip0044Account0RowName) 791 if serializedRow == nil { 792 return errors.E(errors.IO, "missing SLIP0044 coin type account row") 793 } 794 accountID := uint32ToBytes(0) 795 row, err := deserializeAccountRow(accountID, serializedRow) 796 if err != nil { 797 return err 798 } 799 if row.acctType != actBIP0044Legacy { 800 err := errors.Errorf("invalid SLIP0044 account 0 row type %d", row.acctType) 801 return errors.E(errors.IO, err) 802 } 803 bip0044Row, err := deserializeBIP0044AccountRow(accountID, row, initialVersion) 804 if err != nil { 805 return err 806 } 807 // The SLIP0044 account row is written in the legacy account 808 // serialization (used prior to database version 809 // accountVariablesVersion) and must be converted to the new account 810 // format before rewriting the default account. 811 slip0044Account := new(dbBIP0044Account) 812 slip0044Account.dbAccountRow = bip0044Row.dbAccountRow 813 slip0044Account.dbAccountRow.acctType = actBIP0044 814 slip0044Account.pubKeyEncrypted = bip0044Row.pubKeyEncrypted 815 slip0044Account.privKeyEncrypted = bip0044Row.privKeyEncrypted 816 slip0044Account.lastUsedExternalIndex = bip0044Row.lastUsedExternalIndex 817 slip0044Account.lastUsedInternalIndex = bip0044Row.lastUsedInternalIndex 818 slip0044Account.lastReturnedExternalIndex = bip0044Row.lastReturnedExternalIndex 819 slip0044Account.lastReturnedInternalIndex = bip0044Row.lastReturnedInternalIndex 820 slip0044Account.name = acctProps.AccountName // Keep previous name 821 slip0044Account.dbAccountRow.rawData = slip0044Account.serializeRow() 822 823 err = putNewBIP0044Account(ns, 0, slip0044Account) 824 if err != nil { 825 return err 826 } 827 err = mainBucket.Delete(slip0044Account0RowName) 828 if err != nil { 829 return errors.E(errors.IO, err) 830 } 831 832 // Acquire the manager mutex for the remainder of the call so that caches 833 // can be updated. 834 defer m.mtx.Unlock() 835 m.mtx.Lock() 836 837 // Check if the account info cache exists and must be updated for the 838 // SLIP044 coin type derivations. 839 acctInfo, ok := m.acctInfo[0] 840 if !ok { 841 return nil 842 } 843 844 // Decrypt the SLIP0044 coin type account xpub so the in memory account 845 // information can be updated. 846 acctExtPubKeyStr, err := m.cryptoKeyPub.Decrypt(slip0044Account.pubKeyEncrypted) 847 if err != nil { 848 return errors.E(errors.Crypto, errors.Errorf("decrypt SLIP0044 account 0 xpub: %v", err)) 849 } 850 acctExtPubKey, err := hdkeychain.NewKeyFromString(string(acctExtPubKeyStr), m.chainParams) 851 if err != nil { 852 return errors.E(errors.IO, err) 853 } 854 855 // When unlocked, decrypt the SLIP0044 coin type account xpriv as well. 856 var acctExtPrivKey *hdkeychain.ExtendedKey 857 if !m.locked { 858 acctExtPrivKeyStr, err := m.cryptoKeyPriv.Decrypt(slip0044Account.privKeyEncrypted) 859 if err != nil { 860 return errors.E(errors.Crypto, errors.Errorf("decrypt SLIP0044 account 0 xpriv: %v", err)) 861 } 862 acctExtPrivKey, err = hdkeychain.NewKeyFromString(string(acctExtPrivKeyStr), m.chainParams) 863 if err != nil { 864 return errors.E(errors.IO, err) 865 } 866 } 867 868 acctInfo.acctKeyEncrypted = slip0044Account.privKeyEncrypted 869 acctInfo.acctKeyPriv = acctExtPrivKey 870 acctInfo.acctKeyPub = acctExtPubKey 871 872 return nil 873 } 874 875 // deriveKeyFromPath returns either a public or private derived extended key 876 // based on the private flag for the given an account, branch, and index. 877 // 878 // This function MUST be called with the manager lock held for writes. 879 func (m *Manager) deriveKeyFromPath(ns walletdb.ReadBucket, account, branch, index uint32, private bool) (*hdkeychain.ExtendedKey, error) { 880 if private && account == ImportedAddrAccount { 881 return nil, errors.E(errors.Invalid, "account does not record private keys") 882 } 883 884 // Look up the account key information. 885 acctInfo, err := m.loadAccountInfo(ns, account) 886 if err != nil { 887 return nil, err 888 } 889 890 return deriveKey(acctInfo, branch, index, private) 891 } 892 893 // chainAddressRowToManaged returns a new managed address based on chained 894 // address data loaded from the database. 895 // 896 // This function MUST be called with the manager lock held for writes. 897 func (m *Manager) chainAddressRowToManaged(ns walletdb.ReadBucket, row *dbChainAddressRow) (ManagedAddress, error) { 898 private := !m.locked 899 if row.account > ImportedAddrAccount { 900 private = false 901 } else if set, unlocked := m.accountHasPassphrase(ns, row.account); set { 902 private = unlocked 903 } 904 addressKey, err := m.deriveKeyFromPath(ns, row.account, row.branch, 905 row.index, private) 906 if err != nil { 907 return nil, err 908 } 909 910 // Create serialized pubkey. Zero the extended key only if it is 911 // private. A public key copy must be made if the extended key is 912 // private, otherwise it may be unintentionally zeroed as well. 913 pubKey := addressKey.SerializedPubKey() 914 if addressKey.IsPrivate() { 915 defer addressKey.Zero() 916 pubKey = append(pubKey[:0:0], pubKey...) 917 } 918 919 return m.keyToManaged(pubKey, row.account, row.branch, row.index) 920 } 921 922 // importedAddressRowToManaged returns a new managed address based on imported 923 // address data loaded from the database. 924 func (m *Manager) importedAddressRowToManaged(row *dbImportedAddressRow) (ManagedAddress, error) { 925 // Use the crypto public key to decrypt the imported public key. 926 pubBytes, err := m.cryptoKeyPub.Decrypt(row.encryptedPubKey) 927 if err != nil { 928 return nil, errors.E(errors.Crypto, errors.Errorf("decrypt imported pubkey: %v", err)) 929 } 930 931 ma, err := newManagedAddressWithoutPrivKey(m, row.account, pubBytes) 932 if err != nil { 933 return nil, err 934 } 935 ma.imported = true 936 937 return ma, nil 938 } 939 940 // scriptAddressRowToManaged returns a new managed address based on script 941 // address data loaded from the database. 942 func (m *Manager) scriptAddressRowToManaged(row *dbScriptAddressRow) (ManagedAddress, error) { 943 // Use the crypto public key to decrypt the imported script hash. 944 scriptHash, err := m.cryptoKeyPub.Decrypt(row.encryptedHash) 945 if err != nil { 946 return nil, errors.E(errors.Crypto, errors.Errorf("decrypt imported P2SH address: %v", err)) 947 } 948 949 return newScriptAddress(m, row.account, scriptHash, row.script) 950 } 951 952 // rowInterfaceToManaged returns a new managed address based on the given 953 // address data loaded from the database. It will automatically select the 954 // appropriate type. 955 // 956 // This function MUST be called with the manager lock held for writes. 957 func (m *Manager) rowInterfaceToManaged(ns walletdb.ReadBucket, rowInterface interface{}) (ManagedAddress, error) { 958 switch row := rowInterface.(type) { 959 case *dbChainAddressRow: 960 return m.chainAddressRowToManaged(ns, row) 961 962 case *dbImportedAddressRow: 963 return m.importedAddressRowToManaged(row) 964 965 case *dbScriptAddressRow: 966 return m.scriptAddressRowToManaged(row) 967 } 968 969 return nil, errors.E(errors.Invalid, errors.Errorf("address type %T", rowInterface)) 970 } 971 972 // addressID returns the internal database key used to record an address. This 973 // is currently the address' pubkey or script hash160, and other address types 974 // are unsupported. 975 func addressID(address stdaddr.Address) ([]byte, error) { 976 switch address := address.(type) { 977 case stdaddr.Hash160er: 978 return address.Hash160()[:], nil 979 default: 980 return nil, errors.E(errors.Invalid, errors.Errorf("address "+ 981 "id cannot be created from type %T (requires Hash160 method)", 982 address)) 983 } 984 } 985 986 // loadAddress attempts to load the passed address from the database. 987 // 988 // This function MUST be called with the manager lock held for writes. 989 func (m *Manager) loadAddress(ns walletdb.ReadBucket, address stdaddr.Address) (ManagedAddress, error) { 990 // Attempt to load the raw address information from the database. 991 id, err := addressID(normalizeAddress(address)) 992 if err != nil { 993 return nil, err 994 } 995 rowInterface, err := fetchAddress(ns, id) 996 if err != nil { 997 if errors.Is(err, errors.NotExist) { 998 return nil, errors.E(errors.NotExist, errors.Errorf("no address %s", address)) 999 } 1000 return nil, err 1001 } 1002 1003 // Create a new managed address for the specific type of address based 1004 // on type. 1005 return m.rowInterfaceToManaged(ns, rowInterface) 1006 } 1007 1008 // Address returns a managed address given the passed address if it is known 1009 // to the address manager. A managed address differs from the passed address 1010 // in that it also potentially contains extra information needed to sign 1011 // transactions such as the associated private key for pay-to-pubkey and 1012 // pay-to-pubkey-hash addresses and the script associated with 1013 // pay-to-script-hash addresses. 1014 func (m *Manager) Address(ns walletdb.ReadBucket, address stdaddr.Address) (ManagedAddress, error) { 1015 address = normalizeAddress(address) 1016 defer m.mtx.Unlock() 1017 m.mtx.Lock() 1018 ma, err := m.loadAddress(ns, address) 1019 return ma, err 1020 } 1021 1022 // AddrAccount returns the account to which the given address belongs. 1023 func (m *Manager) AddrAccount(ns walletdb.ReadBucket, address stdaddr.Address) (uint32, error) { 1024 id, err := addressID(normalizeAddress(address)) 1025 if err != nil { 1026 return 0, err 1027 } 1028 acct, err := fetchAddrAccount(ns, id) 1029 if err != nil { 1030 if errors.Is(err, errors.NotExist) { 1031 return 0, errors.E(errors.NotExist, errors.Errorf("no address %v", address)) 1032 } 1033 return 0, err 1034 } 1035 1036 return acct, nil 1037 } 1038 1039 // ChangePassphrase changes either the public or private passphrase to the 1040 // provided value depending on the private flag. In order to change the private 1041 // password, the address manager must not be watching-only. The new passphrase 1042 // keys are derived using the scrypt parameters in the options, so changing the 1043 // passphrase may be used to bump the computational difficulty needed to brute 1044 // force the passphrase. 1045 func (m *Manager) ChangePassphrase(ns walletdb.ReadWriteBucket, oldPassphrase, newPassphrase []byte, private bool) error { 1046 defer m.mtx.Unlock() 1047 m.mtx.Lock() 1048 1049 // No private passphrase to change for a watching-only address manager. 1050 if private && m.watchingOnly { 1051 return errors.E(errors.WatchingOnly) 1052 } 1053 1054 // Ensure the provided old passphrase is correct. This check is done 1055 // using a copy of the appropriate master key depending on the private 1056 // flag to ensure the current state is not altered. The temp key is 1057 // cleared when done to avoid leaving a copy in memory. 1058 secretKey := snacl.SecretKey{Key: &snacl.CryptoKey{}} 1059 if private { 1060 secretKey.Parameters = m.masterKeyPriv.Parameters 1061 } else { 1062 secretKey.Parameters = m.masterKeyPub.Parameters 1063 } 1064 if err := secretKey.DeriveKey(&oldPassphrase); err != nil { 1065 return err 1066 } 1067 defer secretKey.Zero() 1068 1069 // Generate a new master key from the passphrase which is used to secure 1070 // the actual secret keys. 1071 newMasterKey, err := newSecretKey(&newPassphrase, scryptOptionsForNet(m.chainParams.Net)) 1072 if err != nil { 1073 return err 1074 } 1075 newKeyParams := newMasterKey.Marshal() 1076 1077 if private { 1078 // Technically, the locked state could be checked here to only 1079 // do the decrypts when the address manager is locked as the 1080 // clear text keys are already available in memory when it is 1081 // unlocked, but this is not a hot path, decryption is quite 1082 // fast, and it's less cyclomatic complexity to simply decrypt 1083 // in either case. 1084 1085 // Create a new passphrase hasher. 1086 hashKey := make([]byte, 32) 1087 _, err := io.ReadFull(rand.Reader, hashKey) 1088 if err != nil { 1089 return errors.E(errors.IO, err) 1090 } 1091 passHasher, err := blake2b.New256(hashKey) 1092 if err != nil { 1093 return err 1094 } 1095 1096 // Re-encrypt the crypto private key using the new master 1097 // private key. 1098 decPriv, err := secretKey.Decrypt(m.cryptoKeyPrivEncrypted) 1099 if err != nil { 1100 return errors.E(errors.Crypto, errors.Errorf("decrypt crypto privkey: %v", err)) 1101 } 1102 encPriv, err := newMasterKey.Encrypt(decPriv) 1103 zero(decPriv) 1104 if err != nil { 1105 return errors.E(errors.Crypto, errors.Errorf("encrypt crypto privkey: %v", err)) 1106 } 1107 1108 // When the manager is locked, ensure the new clear text master 1109 // key is cleared from memory now that it is no longer needed. 1110 // If unlocked, create the new passphrase hash with the new 1111 // keyed hash. 1112 var passHash []byte 1113 if m.locked { 1114 newMasterKey.Zero() 1115 } else { 1116 passHasher.Reset() 1117 passHasher.Write(newPassphrase) 1118 passHash = passHasher.Sum(nil) 1119 } 1120 1121 // Save the new keys and params to the db in a single transaction. 1122 err = putCryptoKeys(ns, nil, encPriv) 1123 if err != nil { 1124 return err 1125 } 1126 1127 err = putMasterKeyParams(ns, nil, newKeyParams) 1128 if err != nil { 1129 return err 1130 } 1131 1132 // Now that the db has been successfully updated, clear the old 1133 // key and set the new one. 1134 copy(m.cryptoKeyPrivEncrypted, encPriv) 1135 m.masterKeyPriv.Zero() // Clear the old key. 1136 m.masterKeyPriv = newMasterKey 1137 m.privPassphraseHasher = passHasher 1138 m.privPassphraseHash = passHash 1139 } else { 1140 // Re-encrypt the crypto public key using the new master public 1141 // key. 1142 encryptedPub, err := newMasterKey.Encrypt(m.cryptoKeyPub.Bytes()) 1143 if err != nil { 1144 return errors.E(errors.Crypto, errors.Errorf("encrypt crypto pubkey: %v", err)) 1145 } 1146 1147 // Save the new keys and params to the db in a single transaction. 1148 err = putCryptoKeys(ns, encryptedPub, nil) 1149 if err != nil { 1150 return err 1151 } 1152 1153 err = putMasterKeyParams(ns, newKeyParams, nil) 1154 if err != nil { 1155 return err 1156 } 1157 1158 // Now that the db has been successfully updated, clear the old 1159 // key and set the new one. 1160 m.masterKeyPub.Zero() 1161 m.masterKeyPub = newMasterKey 1162 } 1163 1164 return nil 1165 } 1166 1167 // ConvertToWatchingOnly converts the current address manager to a locked 1168 // watching-only address manager. 1169 // 1170 // WARNING: This function removes private keys from the existing address manager 1171 // which means they will no longer be available. Typically the caller will make 1172 // a copy of the existing wallet database and modify the copy since otherwise it 1173 // would mean permanent loss of any imported private keys. 1174 // 1175 // Executing this function on a manager that is already watching-only will have 1176 // no effect. 1177 func (m *Manager) ConvertToWatchingOnly(ns walletdb.ReadWriteBucket) error { 1178 m.mtx.Lock() 1179 defer m.mtx.Unlock() 1180 1181 // Exit now if the manager is already watching-only. 1182 if m.watchingOnly { 1183 return nil 1184 } 1185 1186 // Remove all private key material and mark the new database as watching 1187 // only. 1188 err := deletePrivateKeys(ns, DBVersion) 1189 if err != nil { 1190 return err 1191 } 1192 1193 err = putWatchingOnly(ns, true) 1194 if err != nil { 1195 return err 1196 } 1197 1198 // Lock the manager to remove all clear text private key material from 1199 // memory if needed. 1200 if !m.locked { 1201 m.lock() 1202 } 1203 1204 // This section clears and removes the encrypted private key material that 1205 // is ordinarily used to unlock the manager. Since the manager is being 1206 // converted to watching-only, the encrypted private key material is no 1207 // longer needed. 1208 1209 // Clear and remove all of the encrypted acount private keys. 1210 for _, acctInfo := range m.acctInfo { 1211 zero(acctInfo.acctKeyEncrypted) 1212 acctInfo.acctKeyEncrypted = nil 1213 } 1214 1215 // Clear and remove encrypted private crypto key. 1216 zero(m.cryptoKeyPrivEncrypted) 1217 m.cryptoKeyPrivEncrypted = nil 1218 m.cryptoKeyPriv = nil 1219 1220 // The master private key is derived from a passphrase when the manager 1221 // is unlocked, so there is no encrypted version to zero. However, 1222 // it is no longer needed, so nil it. 1223 m.masterKeyPriv = nil 1224 1225 // Mark the manager watching-only. 1226 m.watchingOnly = true 1227 return nil 1228 } 1229 1230 // ExistsHash160 returns whether or not the 20 byte P2PKH or P2SH HASH160 is 1231 // known to the address manager. 1232 func (m *Manager) ExistsHash160(ns walletdb.ReadBucket, hash160 []byte) bool { 1233 return existsAddress(ns, hash160) 1234 } 1235 1236 // ImportPrivateKey imports a WIF private key into the address manager. The 1237 // imported address is created using either a compressed or uncompressed 1238 // serialized public key, depending on the CompressPubKey bool of the WIF. 1239 // 1240 // All imported addresses will be part of the account defined by the 1241 // ImportedAddrAccount constant. 1242 // 1243 // NOTE: When the address manager is watching-only, the private key itself will 1244 // not be stored or available since it is private data. Instead, only the 1245 // public key will be stored. This means it is paramount the private key is 1246 // kept elsewhere as the watching-only address manager will NOT ever have access 1247 // to it. 1248 // 1249 // This function will return an error if the address manager is locked and not 1250 // watching-only, or not for the same network as the key trying to be imported. 1251 // It will also return an error if the address already exists. Any other errors 1252 // returned are generally unexpected. 1253 func (m *Manager) ImportPrivateKey(ns walletdb.ReadWriteBucket, wif *dcrutil.WIF) (ManagedPubKeyAddress, error) { 1254 defer m.mtx.Unlock() 1255 m.mtx.Lock() 1256 1257 // The manager must be unlocked to encrypt the imported private key. 1258 if !m.watchingOnly && m.locked { 1259 return nil, errors.E(errors.Locked) 1260 } 1261 1262 // Prevent duplicates. 1263 serializedPubKey := wif.PubKey() 1264 pubKeyHash := dcrutil.Hash160(serializedPubKey) 1265 if existsAddress(ns, pubKeyHash) { 1266 return nil, errors.E(errors.Exist, "address for private key already exists") 1267 } 1268 1269 // Encrypt public key. 1270 encryptedPubKey, err := m.cryptoKeyPub.Encrypt(serializedPubKey) 1271 if err != nil { 1272 return nil, errors.E(errors.Crypto, errors.Errorf("encrypt imported pubkey: %v", err)) 1273 } 1274 1275 // Encrypt the private key when not a watching-only address manager. 1276 var encryptedPrivKey []byte 1277 if !m.watchingOnly { 1278 privKeyBytes := wif.PrivKey() 1279 encryptedPrivKey, err = m.cryptoKeyPriv.Encrypt(privKeyBytes) 1280 zero(privKeyBytes) 1281 if err != nil { 1282 return nil, errors.E(errors.Crypto, errors.Errorf("encrypt imported privkey: %v", err)) 1283 } 1284 } 1285 1286 // Save the new imported address to the db and update start block (if 1287 // needed) in a single transaction. 1288 err = putImportedAddress(ns, pubKeyHash, ImportedAddrAccount, 1289 encryptedPubKey, encryptedPrivKey) 1290 if err != nil { 1291 return nil, err 1292 } 1293 1294 // Create a new managed address based on the imported address. 1295 managedAddr, err := newManagedAddressWithoutPrivKey(m, ImportedAddrAccount, 1296 serializedPubKey) 1297 if err != nil { 1298 return nil, err 1299 } 1300 managedAddr.imported = true 1301 return managedAddr, nil 1302 } 1303 1304 // ImportPubKey imports a compressed 33-byte serialized secp256k1 public key and 1305 // the derived P2PKH address. This method may only be used by watching-only 1306 // wallets. 1307 func (m *Manager) ImportPublicKey(ns walletdb.ReadWriteBucket, pubkey []byte) (ManagedPubKeyAddress, error) { 1308 defer m.mtx.Unlock() 1309 m.mtx.Lock() 1310 1311 if !m.watchingOnly { 1312 return nil, errors.E(errors.Invalid, "public keys may "+ 1313 "only be imported by watching-only wallets") 1314 } 1315 1316 if len(pubkey) != secp256k1.PubKeyBytesLenCompressed { 1317 return nil, errors.E(errors.Encoding, "invalid length for "+ 1318 "compressed pubkey") 1319 } 1320 switch pubkey[0] { 1321 case secp256k1.PubKeyFormatCompressedEven, 1322 secp256k1.PubKeyFormatCompressedOdd: 1323 default: 1324 return nil, errors.E(errors.Encoding, "invalid format byte "+ 1325 "for compressed pubkey") 1326 } 1327 1328 // Prevent duplicates. 1329 pkh := dcrutil.Hash160(pubkey) 1330 if existsAddress(ns, pkh) { 1331 return nil, errors.E(errors.Exist, "address for public key "+ 1332 "already exists") 1333 } 1334 1335 // Encrypt public key. 1336 encryptedPubKey, err := m.cryptoKeyPub.Encrypt(pubkey) 1337 if err != nil { 1338 return nil, errors.E(errors.Crypto, 1339 errors.Errorf("encrypt imported pubkey: %v", err)) 1340 } 1341 1342 // Save the new imported address to the db and update start block (if 1343 // needed) in a single transaction. 1344 err = putImportedAddress(ns, pkh, ImportedAddrAccount, 1345 encryptedPubKey, nil) 1346 if err != nil { 1347 return nil, err 1348 } 1349 1350 // Create a new managed address based on the imported address. 1351 managedAddr, err := newManagedAddressWithoutPrivKey(m, 1352 ImportedAddrAccount, pubkey) 1353 if err != nil { 1354 return nil, err 1355 } 1356 managedAddr.imported = true 1357 return managedAddr, nil 1358 } 1359 1360 // ImportScript imports a user-provided script into the address manager. The 1361 // imported script will act as a pay-to-script-hash address. 1362 // 1363 // All imported script addresses will be part of the account defined by the 1364 // ImportedAddrAccount constant. 1365 func (m *Manager) ImportScript(ns walletdb.ReadWriteBucket, script []byte) (ManagedScriptAddress, error) { 1366 m.mtx.Lock() 1367 defer m.mtx.Unlock() 1368 1369 // Prevent duplicates. 1370 scriptHash := dcrutil.Hash160(script) 1371 if existsAddress(ns, scriptHash) { 1372 return nil, errors.E(errors.Exist, "script already exists") 1373 } 1374 1375 // Encrypt the script hash using the crypto public key so it is 1376 // accessible when the address manager is locked or watching-only. 1377 encryptedHash, err := m.cryptoKeyPub.Encrypt(scriptHash) 1378 if err != nil { 1379 return nil, errors.E(errors.Crypto, errors.Errorf("encrypt script hash: %v", err)) 1380 } 1381 1382 // Save the new imported address to the db and update start block (if 1383 // needed) in a single transaction. 1384 err = putScriptAddress(ns, scriptHash, ImportedAddrAccount, 1385 encryptedHash, script) 1386 if err != nil { 1387 return nil, err 1388 } 1389 1390 // Create a new managed address based on the imported script. 1391 return newScriptAddress(m, ImportedAddrAccount, scriptHash, script) 1392 } 1393 1394 func (m *Manager) ImportXpubAccount(ns walletdb.ReadWriteBucket, name string, xpub *hdkeychain.ExtendedKey) error { 1395 defer m.mtx.Unlock() 1396 m.mtx.Lock() 1397 1398 // Validate account name 1399 if err := ValidateAccountName(name); err != nil { 1400 return err 1401 } 1402 1403 // There may not be an account by the same name 1404 if _, err := fetchAccountByName(ns, name); err == nil { 1405 return errors.E(errors.Exist, "account name in use") 1406 } 1407 1408 // Reserve next imported account number 1409 account, err := fetchLastImportedAccount(ns) 1410 if err != nil { 1411 return err 1412 } 1413 account++ 1414 if account < MaxAccountNum { 1415 return errors.E(errors.Invalid, "exhausted possible imported accounts") 1416 } 1417 1418 // Encrypt the default account keys with the associated crypto keys. 1419 apes := xpub.String() 1420 acctPubEnc, err := m.cryptoKeyPub.Encrypt([]byte(apes)) 1421 if err != nil { 1422 return errors.E(errors.Crypto, errors.Errorf("encrypt account pubkey: %v", err)) 1423 } 1424 // We have the encrypted account extended keys, so save them to the 1425 // database 1426 dbAcct := new(dbBIP0044Account) 1427 dbAcct.acctType = actBIP0044 1428 dbAcct.pubKeyEncrypted = acctPubEnc 1429 dbAcct.lastUsedExternalIndex = ^uint32(0) 1430 dbAcct.lastUsedInternalIndex = ^uint32(0) 1431 dbAcct.lastReturnedExternalIndex = ^uint32(0) 1432 dbAcct.lastReturnedInternalIndex = ^uint32(0) 1433 dbAcct.name = name 1434 dbAcct.rawData = dbAcct.serializeRow() 1435 err = putNewBIP0044Account(ns, account, dbAcct) 1436 if err != nil { 1437 return err 1438 } 1439 1440 // Save last imported account metadata 1441 if err := putLastImportedAccount(ns, account); err != nil { 1442 return err 1443 } 1444 1445 return nil 1446 } 1447 1448 // IsLocked returns whether or not the address managed is locked. When it is 1449 // unlocked, the decryption key needed to decrypt private keys used for signing 1450 // is in memory. 1451 func (m *Manager) IsLocked() bool { 1452 m.mtx.RLock() 1453 defer m.mtx.RUnlock() 1454 1455 return m.locked 1456 } 1457 1458 // Lock performs a best try effort to remove and zero all secret keys associated 1459 // with the address manager. 1460 // 1461 // This function will return an error if invoked on a watching-only address 1462 // manager. 1463 func (m *Manager) Lock() error { 1464 // A watching-only address manager can't be locked. 1465 if m.watchingOnly { 1466 return errors.E(errors.WatchingOnly) 1467 } 1468 1469 m.mtx.Lock() 1470 defer m.mtx.Unlock() 1471 1472 // Error on attempt to lock an already locked manager. 1473 if m.locked { 1474 return errors.E(errors.Locked) 1475 } 1476 1477 m.lock() 1478 return nil 1479 } 1480 1481 // LookupAccount loads account number stored in the manager for the given 1482 // account name 1483 func (m *Manager) LookupAccount(ns walletdb.ReadBucket, name string) (uint32, error) { 1484 // Mutex does not need to be held here as this does not read or write to any 1485 // of the manager's members. 1486 return fetchAccountByName(ns, name) 1487 } 1488 1489 // UnlockedWithPassphrase returns nil when the wallet is currently unlocked with a 1490 // matching passphrase and errors with the following codes otherwise: 1491 // 1492 // WatchingOnly: The wallet is watching-only and can never be unlocked 1493 // Locked: The wallet is currently locked 1494 // Passphrase: The wallet is unlocked but the provided passphrase is incorrect 1495 func (m *Manager) UnlockedWithPassphrase(passphrase []byte) error { 1496 defer m.mtx.RUnlock() 1497 m.mtx.RLock() 1498 1499 if m.watchingOnly { 1500 return errors.E(errors.WatchingOnly, "watching wallets can not be unlocked") 1501 } 1502 1503 if m.locked { 1504 return errors.E(errors.Locked) 1505 } 1506 1507 m.privPassphraseHasherMu.Lock() 1508 m.privPassphraseHasher.Reset() 1509 m.privPassphraseHasher.Write(passphrase) 1510 passHash := m.privPassphraseHasher.Sum(nil) 1511 m.privPassphraseHasherMu.Unlock() 1512 1513 if subtle.ConstantTimeCompare(passHash, m.privPassphraseHash) != 1 { 1514 return errors.E(errors.Passphrase) 1515 } 1516 1517 return nil 1518 } 1519 1520 // Unlock derives the master private key from the specified passphrase. An 1521 // invalid passphrase will return an error. Otherwise, the derived secret key 1522 // is stored in memory until the address manager is locked. Any failures that 1523 // occur during this function will result in the address manager being locked, 1524 // even if it was already unlocked prior to calling this function. 1525 // 1526 // This function will return an error if invoked on a watching-only address 1527 // manager. 1528 func (m *Manager) Unlock(ns walletdb.ReadBucket, passphrase []byte) error { 1529 defer m.mtx.Unlock() 1530 m.mtx.Lock() 1531 1532 // A watching-only address manager can't be unlocked. 1533 if m.watchingOnly { 1534 return errors.E(errors.WatchingOnly, "cannot unlock watching wallet") 1535 } 1536 1537 m.privPassphraseHasherMu.Lock() 1538 m.privPassphraseHasher.Reset() 1539 m.privPassphraseHasher.Write(passphrase) 1540 passHash := m.privPassphraseHasher.Sum(nil) 1541 m.privPassphraseHasherMu.Unlock() 1542 1543 // Avoid actually unlocking if the manager is already unlocked 1544 // and the passphrases match. 1545 if !m.locked { 1546 // compare passphrase hashes 1547 if subtle.ConstantTimeCompare(passHash, m.privPassphraseHash) != 1 { 1548 m.lock() 1549 return errors.E(errors.Passphrase) 1550 } 1551 return nil 1552 } 1553 1554 // Derive the master private key using the provided passphrase. 1555 if err := m.masterKeyPriv.DeriveKey(&passphrase); err != nil { 1556 m.lock() 1557 return err 1558 } 1559 1560 // Use the master private key to decrypt the crypto private key. 1561 decryptedKey, err := m.masterKeyPriv.Decrypt(m.cryptoKeyPrivEncrypted) 1562 if err != nil { 1563 m.lock() 1564 return errors.E(errors.Crypto, errors.Errorf("decrypt crypto privkey: %v", err)) 1565 } 1566 m.cryptoKeyPriv.CopyBytes(decryptedKey) 1567 zero(decryptedKey) 1568 1569 // Use the crypto private key to decrypt all of the account private 1570 // extended keys. 1571 for account, acctInfo := range m.acctInfo { 1572 if len(acctInfo.acctKeyEncrypted) == 0 { 1573 continue 1574 } 1575 if acctInfo.uniqueKey != nil { 1576 // not encrypted by m.cryptoKeyPriv 1577 continue 1578 } 1579 decrypted, err := m.cryptoKeyPriv.Decrypt(acctInfo.acctKeyEncrypted) 1580 if err != nil { 1581 m.lock() 1582 return errors.E(errors.Crypto, errors.Errorf("decrypt account %d privkey: %v", account, err)) 1583 } 1584 1585 acctKeyPriv, err := hdkeychain.NewKeyFromString(string(decrypted), m.chainParams) 1586 zero(decrypted) 1587 if err != nil { 1588 m.lock() 1589 return errors.E(errors.IO, err) 1590 } 1591 acctInfo.acctKeyPriv = acctKeyPriv 1592 } 1593 1594 m.locked = false 1595 m.privPassphraseHash = passHash 1596 return nil 1597 } 1598 1599 // UnlockAccount decrypts a uniquely-encrypted account's private keys. 1600 func (m *Manager) UnlockAccount(dbtx walletdb.ReadTx, account uint32, 1601 passphrase []byte) error { 1602 1603 ns := dbtx.ReadBucket(waddrmgrBucketKey) 1604 1605 defer m.mtx.Unlock() 1606 m.mtx.Lock() 1607 1608 // A watching-only address manager can only be locked/unlocked for 1609 // imported accounts. 1610 if m.watchingOnly && account < ImportedAddrAccount { 1611 return errors.E(errors.WatchingOnly, 1612 "cannot unlock watching wallet") 1613 } 1614 1615 acctInfo, err := m.loadAccountInfo(ns, account) 1616 if err != nil { 1617 return err 1618 } 1619 if acctInfo.uniqueKey == nil { 1620 return errors.E(errors.Crypto, "account is not "+ 1621 "encrypted with a unique passphrase") 1622 } 1623 1624 // Using a hash object (keyed at runtime with random bytes), hash the 1625 // passphrase to compare with an existing unlocked account, or to record 1626 // its passphrase hash for later authentication of an already unlocked 1627 // account without deriving a key. 1628 acctInfo.uniquePassHasher.Reset() 1629 acctInfo.uniquePassHasher.Write(passphrase) 1630 passHash := acctInfo.uniquePassHasher.Sum(nil) 1631 1632 if acctInfo.acctKeyPriv != nil { 1633 // already unlocked. compare passphrase hashes. 1634 if subtle.ConstantTimeCompare(passHash, acctInfo.uniquePassHash) != 1 { 1635 return errors.E(errors.Passphrase) 1636 } 1637 return nil 1638 } 1639 kdfp := acctInfo.uniqueKey 1640 key := argon2idKey(passphrase, kdfp) 1641 defer zero(key) 1642 plaintext, err := unseal(key, acctInfo.acctKeyEncrypted) 1643 defer zero(plaintext) 1644 if err != nil { 1645 return err 1646 } 1647 1648 acctKeyPriv, err := hdkeychain.NewKeyFromString(string(plaintext), 1649 m.chainParams) 1650 if err != nil { 1651 return errors.E(errors.IO, err) 1652 } 1653 acctInfo.acctKeyPriv = acctKeyPriv 1654 acctInfo.uniquePassHash = passHash 1655 1656 return nil 1657 } 1658 1659 // LockAccount locks an individually-encrypted account by removing private key 1660 // access until unlocked again. 1661 func (m *Manager) LockAccount(dbtx walletdb.ReadTx, account uint32) error { 1662 ns := dbtx.ReadBucket(waddrmgrBucketKey) 1663 1664 defer m.mtx.Unlock() 1665 m.mtx.Lock() 1666 1667 // A watching-only address manager can only be locked/unlocked for 1668 // imported accounts. 1669 if m.watchingOnly && account < ImportedAddrAccount { 1670 return errors.E(errors.WatchingOnly, 1671 "cannot lock watching wallet") 1672 } 1673 1674 acctInfo, err := m.loadAccountInfo(ns, account) 1675 if err != nil { 1676 return err 1677 } 1678 if acctInfo.uniqueKey == nil { 1679 return errors.E(errors.Crypto, "account is not "+ 1680 "encrypted with a unique passphrase") 1681 } 1682 if acctInfo.acctKeyPriv == nil { 1683 return errors.E(errors.Locked, "account is already locked") 1684 } 1685 acctInfo.acctKeyPriv.Zero() 1686 acctInfo.acctKeyPriv = nil 1687 1688 return nil 1689 } 1690 1691 // SetAccountPassphrase individually-encrypts or changes the passphrase for 1692 // account private keys. 1693 // 1694 // If the passphrase has zero length, the private keys are re-encrypted with the 1695 // manager's global passphrase. Cannot be zero length for watching-only wallets. 1696 func (m *Manager) SetAccountPassphrase(dbtx walletdb.ReadWriteTx, account uint32, 1697 passphrase []byte) error { 1698 1699 ns := dbtx.ReadWriteBucket(waddrmgrBucketKey) 1700 1701 defer m.mtx.Unlock() 1702 m.mtx.Lock() 1703 1704 // A watching-only address manager can only be locked/unlocked for 1705 // imported accounts. 1706 if m.watchingOnly { 1707 if account < ImportedAddrAccount { 1708 return errors.E(errors.WatchingOnly, 1709 "cannot set passphrase for watching wallet") 1710 } 1711 // Watching-only wallets must have a passphrase supplied. 1712 if len(passphrase) == 0 { 1713 return errors.E(errors.Passphrase, 1714 "watching-only imported accounts must have a passprase") 1715 } 1716 } 1717 1718 acctInfo, err := m.loadAccountInfo(ns, account) 1719 if err != nil { 1720 return err 1721 } 1722 var needUnlocked string 1723 switch { 1724 case acctInfo.acctKeyPriv == nil && acctInfo.uniqueKey == nil: 1725 needUnlocked = "wallet" 1726 case acctInfo.acctKeyPriv == nil: // uniqueKey != nil 1727 needUnlocked = "account" 1728 } 1729 if needUnlocked != "" { 1730 err := errors.Errorf("%s must be unlocked to set a "+ 1731 "unique account passphrase", needUnlocked) 1732 return errors.E(errors.Locked, err) 1733 } 1734 1735 if len(passphrase) == 0 { 1736 return m.removeAccountPassphrase(ns, account, acctInfo) 1737 } 1738 1739 // Create a new passphase hasher from a new key, and hash the new 1740 // passphrase. 1741 hashKey := make([]byte, 32) 1742 _, err = io.ReadFull(rand.Reader, hashKey) 1743 if err != nil { 1744 return errors.E(errors.IO, err) 1745 } 1746 hasher, err := blake2b.New256(hashKey) 1747 if err != nil { 1748 return errors.E(errors.IO, err) 1749 } 1750 hasher.Write(passphrase) 1751 passHash := hasher.Sum(nil) 1752 1753 // Encrypt the account xpriv with a new key. 1754 kdfp, err := kdf.NewArgon2idParams(rand.Reader) 1755 if err != nil { 1756 return err 1757 } 1758 plaintext := []byte(acctInfo.acctKeyPriv.String()) 1759 key := argon2idKey(passphrase, kdfp) 1760 ciphertext, err := seal(rand.Reader, key, plaintext) 1761 zero(plaintext) 1762 if err != nil { 1763 return err 1764 } 1765 1766 // Record the KDF parameters. 1767 acctKey := uint32ToBytes(account) 1768 vars := ns.NestedReadWriteBucket(acctVarsBucketName). 1769 NestedReadWriteBucket(acctKey) 1770 err = putAccountKDFVar(vars, acctVarKDF, kdfp) 1771 if err != nil { 1772 return err 1773 } 1774 1775 // Write a new account row with the new xpriv ciphertext. 1776 dbAcct, err := fetchDBAccount(ns, account, DBVersion) 1777 if err != nil { 1778 return err 1779 } 1780 switch a := dbAcct.(type) { 1781 case *dbBIP0044Account: 1782 a.privKeyEncrypted = ciphertext 1783 a.rawData = a.serializeRow() 1784 err := putAccountRow(ns, account, &a.dbAccountRow) 1785 if err != nil { 1786 return err 1787 } 1788 default: 1789 return errors.Errorf("unknown account type %T", a) 1790 } 1791 1792 acctInfo.acctKeyEncrypted = ciphertext 1793 acctInfo.uniqueKey = kdfp 1794 acctInfo.uniquePassHasher = hasher 1795 acctInfo.uniquePassHash = passHash 1796 1797 return nil 1798 } 1799 1800 func (m *Manager) removeAccountPassphrase(ns walletdb.ReadWriteBucket, account uint32, 1801 acctInfo *accountInfo) error { 1802 1803 if m.watchingOnly { 1804 return errors.E(errors.WatchingOnly, 1805 "cannot remove passphrase for watching wallet") 1806 } 1807 1808 if m.locked { 1809 return errors.E(errors.Locked, "wallet must be unlocked "+ 1810 "to remove account's unique passphrase") 1811 } 1812 1813 plaintext := []byte(acctInfo.acctKeyPriv.String()) 1814 ciphertext, err := m.cryptoKeyPriv.Encrypt(plaintext) 1815 zero(plaintext) 1816 if err != nil { 1817 err := errors.Errorf("encrypt account %d privkey: %v", account, err) 1818 return errors.E(errors.Crypto, err) 1819 } 1820 1821 acctKey := uint32ToBytes(account) 1822 vars := ns.NestedReadWriteBucket(acctVarsBucketName). 1823 NestedReadWriteBucket(acctKey) 1824 err = vars.Delete(acctVarKDF) 1825 if err != nil { 1826 return errors.E(errors.IO, err) 1827 } 1828 1829 // Write a new account row with the new xpriv ciphertext. 1830 dbAcct, err := fetchDBAccount(ns, account, DBVersion) 1831 if err != nil { 1832 return err 1833 } 1834 switch a := dbAcct.(type) { 1835 case *dbBIP0044Account: 1836 a.privKeyEncrypted = ciphertext 1837 a.rawData = a.serializeRow() 1838 err := putAccountRow(ns, account, &a.dbAccountRow) 1839 if err != nil { 1840 return err 1841 } 1842 default: 1843 return errors.Errorf("unknown account type %T", a) 1844 } 1845 1846 acctInfo.acctKeyEncrypted = ciphertext 1847 acctInfo.uniqueKey = nil 1848 acctInfo.uniquePassHasher = nil 1849 acctInfo.uniquePassHash = nil 1850 1851 return nil 1852 } 1853 1854 // AccountHasPassphrase returns whether an account's keys are currently 1855 // protected by a per-account passphrase, and if so, whether the account is 1856 // currently locked or unlocked. 1857 func (m *Manager) AccountHasPassphrase(dbtx walletdb.ReadTx, account uint32) (hasPassphrase, unlocked bool) { 1858 defer m.mtx.RUnlock() 1859 m.mtx.RLock() 1860 1861 ns := dbtx.ReadBucket(waddrmgrBucketKey) 1862 1863 return m.accountHasPassphrase(ns, account) 1864 } 1865 1866 func (m *Manager) accountHasPassphrase(ns walletdb.ReadBucket, account uint32) (hasPassphrase, unlocked bool) { 1867 acctInfo, err := m.loadAccountInfo(ns, account) 1868 if err != nil { 1869 return 1870 } 1871 hasPassphrase = acctInfo.uniqueKey != nil 1872 if hasPassphrase { 1873 unlocked = acctInfo.acctKeyPriv != nil 1874 } 1875 return 1876 } 1877 1878 // MarkUsed updates usage statistics of a BIP0044 account address so that the 1879 // last used address index can be tracked. There is no effect when called on 1880 // P2SH addresses or any imported addresses. 1881 func (m *Manager) MarkUsed(tx walletdb.ReadWriteTx, address stdaddr.Address) error { 1882 ns := tx.ReadWriteBucket(waddrmgrBucketKey) 1883 1884 address = normalizeAddress(address) 1885 id, err := addressID(address) 1886 if err != nil { 1887 return err 1888 } 1889 dbAddr, err := fetchAddress(ns, id) 1890 if err != nil { 1891 return err 1892 } 1893 bip0044Addr, ok := dbAddr.(*dbChainAddressRow) 1894 if !ok { 1895 return nil 1896 } 1897 1898 account := bip0044Addr.account 1899 branch := bip0044Addr.branch 1900 child := bip0044Addr.index 1901 return m.MarkUsedChildIndex(tx, account, branch, child) 1902 } 1903 1904 // MarkUsedChildIndex marks a BIP0044 account branch child as used. 1905 func (m *Manager) MarkUsedChildIndex(tx walletdb.ReadWriteTx, account, branch, child uint32) error { 1906 ns := tx.ReadWriteBucket(waddrmgrBucketKey) 1907 1908 var lastUsedVarName, lastReturnedVarName []byte 1909 switch branch { 1910 case ExternalBranch: 1911 lastUsedVarName = acctVarLastUsedExternal 1912 lastReturnedVarName = acctVarLastReturnedExternal 1913 case InternalBranch: 1914 lastUsedVarName = acctVarLastUsedInternal 1915 lastReturnedVarName = acctVarLastReturnedInternal 1916 default: 1917 return errors.E(errors.Invalid, errors.Errorf("account branch %d", branch)) 1918 } 1919 1920 acctKey := uint32ToBytes(account) 1921 vars := ns.NestedReadWriteBucket(acctVarsBucketName). 1922 NestedReadWriteBucket(acctKey) 1923 1924 var r accountVarReader 1925 lastUsed := r.getAccountUint32Var(vars, lastUsedVarName) 1926 lastRet := r.getAccountUint32Var(vars, lastReturnedVarName) 1927 if r.err != nil { 1928 return errors.E(errors.IO, r.err) 1929 } 1930 1931 // Change nothing when the child is not beyond the currently-recorded 1932 // last used child index. 1933 if child+1 <= lastUsed+1 { 1934 return nil 1935 } 1936 1937 // Write larger last used child index. 1938 err := putAccountUint32Var(vars, lastUsedVarName, child) 1939 if err != nil { 1940 return err 1941 } 1942 // Increase last returned child if necessary. This value should never 1943 // be lower than the last used child. 1944 if lastRet+1 < child+1 { 1945 err = putAccountUint32Var(vars, lastReturnedVarName, child) 1946 if err != nil { 1947 return err 1948 } 1949 } 1950 1951 return nil 1952 } 1953 1954 // MarkReturnedChildIndex marks a BIP0044 account branch child as returned to a 1955 // caller. This method will write returned child indexes that are lower than 1956 // the currently-recorded last returned indexes, but these indexes will never be 1957 // lower than the last used index. 1958 func (m *Manager) MarkReturnedChildIndex(dbtx walletdb.ReadWriteTx, account, branch, child uint32) error { 1959 ns := dbtx.ReadWriteBucket(waddrmgrBucketKey) 1960 1961 bucketKey := uint32ToBytes(account) 1962 varsBucket := ns.NestedReadWriteBucket(acctVarsBucketName).NestedReadWriteBucket(bucketKey) 1963 varName := acctVarLastReturnedExternal 1964 if branch == 1 { 1965 varName = acctVarLastReturnedInternal 1966 } 1967 var r accountVarReader 1968 lastRet := r.getAccountUint32Var(varsBucket, varName) 1969 if r.err != nil { 1970 return r.err 1971 } 1972 if child > lastRet || lastRet == ^uint32(0) { 1973 err := putAccountUint32Var(varsBucket, varName, child) 1974 if err != nil { 1975 return err 1976 } 1977 } 1978 1979 return nil 1980 } 1981 1982 // ChainParams returns the chain parameters for this address manager. 1983 func (m *Manager) ChainParams() *chaincfg.Params { 1984 // NOTE: No need for mutex here since the net field does not change 1985 // after the manager instance is created. 1986 1987 return m.chainParams 1988 } 1989 1990 // syncAccountToAddrIndex takes an account, branch, and index and synchronizes 1991 // the waddrmgr account to it. 1992 // 1993 // This function MUST be called with the manager lock held for writes. 1994 func (m *Manager) syncAccountToAddrIndex(ns walletdb.ReadWriteBucket, account uint32, syncToIndex uint32, branch uint32) error { 1995 // Unfortunately the imported account is saved as a BIP0044 account type so 1996 // the next db fetch will not error. Therefore we need an explicit check 1997 // that it is not being modified. 1998 if account == ImportedAddrAccount { 1999 return errors.E(errors.Invalid, "cannot sync imported account branch index") 2000 } 2001 2002 // The next address can only be generated for accounts that have already 2003 // been created. This also enforces that the account is a BIP0044 account. 2004 // While imported accounts are also saved as BIP0044 account types, the 2005 // above check prevents this from this code ever continuing on imported 2006 // accounts. 2007 acctInfo, err := m.loadAccountInfo(ns, account) 2008 if err != nil { 2009 return err 2010 } 2011 2012 // Derive the account branch extended key. 2013 var xpubBranch *hdkeychain.ExtendedKey 2014 switch branch { 2015 case ExternalBranch, InternalBranch: 2016 xpubBranch, err = acctInfo.acctKeyPub.Child(branch) 2017 if err != nil { 2018 return err 2019 } 2020 default: 2021 return errors.E(errors.Invalid, errors.Errorf("account branch %d", branch)) 2022 } 2023 2024 // Ensure the requested index to sync to doesn't exceed the maximum 2025 // allowed for this account. 2026 if syncToIndex > MaxAddressesPerAccount { 2027 return errors.E(errors.Invalid, errors.Errorf("child index %d exceeds max", syncToIndex)) 2028 } 2029 2030 // Because the database does not track the last generated address for each 2031 // account (only the address usage in public transactions), child addresses 2032 // must be generated and saved in reverse, down to child index 0. For each 2033 // derived address, a check is performed to see if the address has already 2034 // been recorded. As soon as any already-saved address is found, the loop 2035 // can end, because we know that all addresses before that child have also 2036 // been created. 2037 for child := syncToIndex; ; child-- { 2038 xpubChild, err := xpubBranch.Child(child) 2039 if errors.Is(err, hdkeychain.ErrInvalidChild) { 2040 continue 2041 } 2042 if err != nil { 2043 return err 2044 } 2045 // This can't error as only good input is passed to 2046 // dcrutil.NewAddressPubKeyHash. 2047 addr, _ := compat.HD2Address(xpubChild, m.chainParams) 2048 hash160 := addr.Hash160()[:] 2049 if existsAddress(ns, hash160) { 2050 // address was found and there are no more to generate 2051 break 2052 } 2053 2054 err = putChainedAddress(ns, hash160, account, branch, child) 2055 if err != nil { 2056 return err 2057 } 2058 2059 if child == 0 { 2060 break 2061 } 2062 } 2063 2064 return nil 2065 } 2066 2067 // SyncAccountToAddrIndex records address records for an account branch up to 2068 // syncToIndex. It does not modify the last used or last returned properties of 2069 // the account branch. 2070 func (m *Manager) SyncAccountToAddrIndex(ns walletdb.ReadWriteBucket, account uint32, syncToIndex uint32, branch uint32) error { 2071 defer m.mtx.Unlock() 2072 m.mtx.Lock() 2073 return m.syncAccountToAddrIndex(ns, account, syncToIndex, branch) 2074 } 2075 2076 // ValidateAccountName validates the given account name and returns an error, 2077 // if any. 2078 func ValidateAccountName(name string) error { 2079 if name == "" { 2080 return errors.E(errors.Invalid, "accounts may not be named the empty string") 2081 } 2082 if isReservedAccountName(name) { 2083 return errors.E(errors.Invalid, "reserved account name") 2084 } 2085 return nil 2086 } 2087 2088 // NewAccount creates and returns a new account stored in the manager based 2089 // on the given account name. If an account with the same name already exists, 2090 // ErrDuplicateAccount will be returned. Since creating a new account requires 2091 // access to the cointype keys (from which extended account keys are derived), 2092 // it requires the manager to be unlocked. 2093 func (m *Manager) NewAccount(ns walletdb.ReadWriteBucket, name string) (uint32, error) { 2094 defer m.mtx.Unlock() 2095 m.mtx.Lock() 2096 2097 if m.watchingOnly { 2098 return 0, errors.E(errors.WatchingOnly) 2099 } 2100 2101 if m.locked { 2102 return 0, errors.E(errors.Locked) 2103 } 2104 2105 // Validate account name 2106 if err := ValidateAccountName(name); err != nil { 2107 return 0, err 2108 } 2109 2110 // Check that account with the same name does not exist 2111 _, err := fetchAccountByName(ns, name) 2112 if err == nil { 2113 return 0, errors.E(errors.Exist, errors.Errorf("account named %q already exists", name)) 2114 } 2115 2116 // Reserve the next account number to use as the internal account 2117 // identifier. 2118 account, err := fetchLastAccount(ns) 2119 if err != nil { 2120 return 0, err 2121 } 2122 account++ 2123 2124 // Fetch the cointype key which will be used to derive the next account 2125 // extended keys 2126 _, coinTypePrivEnc, err := fetchCoinTypeKeys(ns) 2127 if err != nil { 2128 return 0, err 2129 } 2130 2131 // Decrypt the cointype key 2132 serializedKeyPriv, err := m.cryptoKeyPriv.Decrypt(coinTypePrivEnc) 2133 if err != nil { 2134 return 0, errors.E(errors.Crypto, errors.Errorf("decrypt cointype privkey: %v", err)) 2135 } 2136 coinTypeKeyPriv, err := hdkeychain.NewKeyFromString( 2137 string(serializedKeyPriv), m.chainParams) 2138 zero(serializedKeyPriv) 2139 if err != nil { 2140 return 0, errors.E(errors.IO, err) 2141 } 2142 2143 // Derive the account key using the cointype key 2144 acctKeyPriv, err := deriveAccountKey(coinTypeKeyPriv, account) 2145 coinTypeKeyPriv.Zero() 2146 if err != nil { 2147 return 0, err 2148 } 2149 acctKeyPub := acctKeyPriv.Neuter() 2150 // Encrypt the default account keys with the associated crypto keys. 2151 apes := acctKeyPub.String() 2152 acctPubEnc, err := m.cryptoKeyPub.Encrypt([]byte(apes)) 2153 if err != nil { 2154 return 0, errors.E(errors.Crypto, errors.Errorf("encrypt account pubkey: %v", err)) 2155 } 2156 apes = acctKeyPriv.String() 2157 acctPrivEnc, err := m.cryptoKeyPriv.Encrypt([]byte(apes)) 2158 if err != nil { 2159 return 0, errors.E(errors.Crypto, errors.Errorf("encrypt account privkey: %v", err)) 2160 } 2161 2162 // Record account to the database 2163 err = putLastAccount(ns, account) 2164 if err != nil { 2165 return 0, err 2166 } 2167 a := &dbBIP0044Account{ 2168 privKeyEncrypted: acctPrivEnc, 2169 pubKeyEncrypted: acctPubEnc, 2170 lastUsedExternalIndex: ^uint32(0), 2171 lastUsedInternalIndex: ^uint32(0), 2172 lastReturnedExternalIndex: ^uint32(0), 2173 lastReturnedInternalIndex: ^uint32(0), 2174 name: name, 2175 } 2176 a.acctType = actBIP0044 2177 a.rawData = a.serializeRow() 2178 err = putNewBIP0044Account(ns, account, a) 2179 if err != nil { 2180 return 0, err 2181 } 2182 2183 return account, nil 2184 } 2185 2186 // ImportVotingAccount imports an account for use with voting into the manager 2187 // based on the given account name. If an account with the same name already 2188 // exists, ErrDuplicateAccount will be returned. A password must be supplied. 2189 // The acctKeyPriv must be for the current network. 2190 func (m *Manager) ImportVotingAccount(dbtx walletdb.ReadWriteTx, acctKeyPriv *hdkeychain.ExtendedKey, 2191 passphrase []byte, name string) (uint32, error) { 2192 defer m.mtx.Unlock() 2193 m.mtx.Lock() 2194 2195 // Ensure passphrase is included. 2196 if len(passphrase) == 0 { 2197 return 0, errors.E(errors.Passphrase, errors.New("passphrase must be specified")) 2198 } 2199 2200 account, err := m.importAccount(dbtx, importedVoting, acctKeyPriv, name) 2201 if err != nil { 2202 return 0, err 2203 } 2204 // Encrypt the account xpriv with a new key. 2205 kdfp, err := kdf.NewArgon2idParams(rand.Reader) 2206 if err != nil { 2207 return 0, err 2208 } 2209 plaintext := []byte(acctKeyPriv.String()) 2210 key := argon2idKey(passphrase, kdfp) 2211 ciphertext, err := seal(rand.Reader, key, plaintext) 2212 zero(plaintext) 2213 if err != nil { 2214 return 0, err 2215 } 2216 2217 // Record the KDF parameters. 2218 ns := dbtx.ReadWriteBucket(waddrmgrBucketKey) 2219 acctKey := uint32ToBytes(account) 2220 vars := ns.NestedReadWriteBucket(acctVarsBucketName). 2221 NestedReadWriteBucket(acctKey) 2222 err = putAccountKDFVar(vars, acctVarKDF, kdfp) 2223 if err != nil { 2224 return 0, err 2225 } 2226 2227 // Write a new account row with the new xpriv ciphertext. 2228 dbAcct, err := fetchDBAccount(ns, account, DBVersion) 2229 if err != nil { 2230 return 0, err 2231 } 2232 switch a := dbAcct.(type) { 2233 case *dbBIP0044Account: 2234 a.privKeyEncrypted = ciphertext 2235 a.rawData = a.serializeRow() 2236 err := putAccountRow(ns, account, &a.dbAccountRow) 2237 if err != nil { 2238 return 0, err 2239 } 2240 default: 2241 return 0, errors.Errorf("unknown account type %T", a) 2242 } 2243 2244 return account, nil 2245 } 2246 2247 // importAccount imports a private extended key as an account with name. The 2248 // returned account number is one plus the last used imported index. The 2249 // manager must be unlocked in order for keys to be encrypted properly. 2250 func (m *Manager) importAccount(dbtx walletdb.ReadWriteTx, acctType accountType, 2251 acctKeyPriv *hdkeychain.ExtendedKey, name string) (uint32, error) { 2252 if err := ValidateAccountName(name); err != nil { 2253 return 0, err 2254 } 2255 2256 if !acctKeyPriv.IsPrivate() { 2257 return 0, errors.E(errors.Invalid, "extended key must be an xpriv") 2258 } 2259 2260 ns := dbtx.ReadWriteBucket(waddrmgrBucketKey) 2261 2262 // Check that account with the same name does not exist 2263 _, err := fetchAccountByName(ns, name) 2264 if err == nil { 2265 return 0, errors.E(errors.Exist, errors.Errorf("account named %q already exists", name)) 2266 } 2267 2268 // Check that this key is not already known to the wallet by checking 2269 // if we have the address of the first index of the external branch. 2270 acctKeyPub := acctKeyPriv.Neuter() 2271 branchKeyPub, err := acctKeyPub.Child(ExternalBranch) 2272 if err != nil { 2273 return 0, errors.E(errors.Invalid, err, "undable to derive external branch") 2274 } 2275 idxKeyPub, err := branchKeyPub.Child(0) 2276 if err != nil { 2277 return 0, errors.E(errors.Invalid, err, "undable to derive index") 2278 } 2279 2280 addressID := stdaddr.Hash160(idxKeyPub.SerializedPubKey()) 2281 if existsAddress(ns, addressID) { 2282 return 0, errors.E(errors.Exist, "address belonging to this key already exists in the database") 2283 } 2284 2285 // Reserve the next account number to use as the internal account 2286 // identifier. 2287 account, err := fetchLastImportedAccount(ns) 2288 if err != nil { 2289 return 0, err 2290 } 2291 account++ 2292 2293 // Encrypt the default account keys with the associated crypto keys. 2294 apes := acctKeyPub.String() 2295 acctPubEnc, err := m.cryptoKeyPub.Encrypt([]byte(apes)) 2296 if err != nil { 2297 return 0, errors.E(errors.Crypto, errors.Errorf("encrypt account pubkey: %v", err)) 2298 } 2299 apes = acctKeyPriv.String() 2300 acctPrivEnc, err := m.cryptoKeyPriv.Encrypt([]byte(apes)) 2301 if err != nil { 2302 return 0, errors.E(errors.Crypto, errors.Errorf("encrypt account privkey: %v", err)) 2303 } 2304 2305 // Record account to the database 2306 err = putLastImportedAccount(ns, account) 2307 if err != nil { 2308 return 0, err 2309 } 2310 a := &dbBIP0044Account{ 2311 pubKeyEncrypted: acctPubEnc, 2312 privKeyEncrypted: acctPrivEnc, 2313 lastUsedExternalIndex: ^uint32(0), 2314 lastUsedInternalIndex: ^uint32(0), 2315 lastReturnedExternalIndex: ^uint32(0), 2316 lastReturnedInternalIndex: ^uint32(0), 2317 name: name, 2318 } 2319 a.acctType = acctType 2320 a.rawData = a.serializeRow() 2321 err = putNewBIP0044Account(ns, account, a) 2322 if err != nil { 2323 return 0, err 2324 } 2325 2326 return account, nil 2327 } 2328 2329 // RecordDerivedAddress adds an address derived from an account key to the 2330 // wallet's database. The branch and child parameters should not have any 2331 // hardened offset applied. 2332 // 2333 // This method will not update the currently-recorded last returned address for 2334 // the account; see MarkReturnedChildIndex to perform this step after recording 2335 // addresses using this method. 2336 // 2337 // This method is limited to P2PKH addresses for BIP0044 and hardened 2338 // purpose accounts only. 2339 func (m *Manager) RecordDerivedAddress(dbtx walletdb.ReadWriteTx, account, branch, child uint32, pubkey []byte) error { 2340 m.mtx.Lock() 2341 defer m.mtx.Unlock() 2342 2343 ns := dbtx.ReadWriteBucket(waddrmgrBucketKey) 2344 2345 hash160 := dcrutil.Hash160(pubkey) 2346 return putChainedAddress(ns, hash160, account, branch, child) 2347 } 2348 2349 // RenameAccount renames an account stored in the manager based on the 2350 // given account number with the given name. If an account with the same name 2351 // already exists, ErrDuplicateAccount will be returned. 2352 func (m *Manager) RenameAccount(ns walletdb.ReadWriteBucket, account uint32, name string) error { 2353 m.mtx.Lock() 2354 defer m.mtx.Unlock() 2355 2356 // Ensure that a reserved account is not being renamed. 2357 if isReservedAccountNum(account) { 2358 return errors.E(errors.Invalid, "reserved account") 2359 } 2360 2361 // Check that account with the new name does not exist 2362 _, err := fetchAccountByName(ns, name) 2363 if err == nil { 2364 return errors.E(errors.Exist, errors.Errorf("account named %q already exists", name)) 2365 } 2366 // Validate account name 2367 if err := ValidateAccountName(name); err != nil { 2368 return err 2369 } 2370 2371 dbAcct, err := fetchDBAccount(ns, account, DBVersion) 2372 if err != nil { 2373 return err 2374 } 2375 var oldName string 2376 switch dbAcct.(type) { 2377 case *dbBIP0044Account: 2378 acctVars := accountVarsBucket(ns, account) 2379 oldName = string(acctVars.Get(acctVarName)) 2380 err := acctVars.Put(acctVarName, []byte(name)) 2381 if err != nil { 2382 return errors.E(errors.IO, err) 2383 } 2384 default: 2385 return errors.Errorf("unknown account type %T", dbAcct) 2386 } 2387 2388 // Rewrite account id -> name and name -> id indexes. 2389 if err = deleteAccountIDIndex(ns, account); err != nil { 2390 return err 2391 } 2392 if err = deleteAccountNameIndex(ns, oldName); err != nil { 2393 return err 2394 } 2395 if err := putAccountIDIndex(ns, account, name); err != nil { 2396 return err 2397 } 2398 if err := putAccountNameIndex(ns, account, name); err != nil { 2399 return err 2400 } 2401 2402 // Update in-memory account info with new name if cached and the db 2403 // write was successful. 2404 if acctInfo, ok := m.acctInfo[account]; ok { 2405 acctInfo.acctName = name 2406 } 2407 return nil 2408 } 2409 2410 // AccountName returns the account name for the given account number 2411 // stored in the manager. 2412 func (m *Manager) AccountName(ns walletdb.ReadBucket, account uint32) (string, error) { 2413 return fetchAccountName(ns, account) 2414 } 2415 2416 // ForEachAccount calls the given function with each account stored in the 2417 // manager, breaking early on error. 2418 func (m *Manager) ForEachAccount(ns walletdb.ReadBucket, fn func(account uint32) error) error { 2419 return forEachAccount(ns, fn) 2420 } 2421 2422 // LastAccount returns the last account stored in the manager. 2423 func (m *Manager) LastAccount(ns walletdb.ReadBucket) (uint32, error) { 2424 return fetchLastAccount(ns) 2425 } 2426 2427 // LastImportedAccount returns the acocunt number of the last imported account. 2428 // This is the reserved imported account unless an account has been created by 2429 // an imported xpub. 2430 func (m *Manager) LastImportedAccount(dbtx walletdb.ReadTx) (uint32, error) { 2431 ns := dbtx.ReadBucket(waddrmgrBucketKey) 2432 return fetchLastImportedAccount(ns) 2433 } 2434 2435 // ForEachAccountAddress calls the given function with each address of 2436 // the given account stored in the manager, breaking early on error. 2437 func (m *Manager) ForEachAccountAddress(ns walletdb.ReadBucket, account uint32, fn func(maddr ManagedAddress) error) error { 2438 m.mtx.Lock() 2439 defer m.mtx.Unlock() 2440 2441 addrFn := func(rowInterface interface{}) error { 2442 managedAddr, err := m.rowInterfaceToManaged(ns, rowInterface) 2443 if err != nil { 2444 return err 2445 } 2446 return fn(managedAddr) 2447 } 2448 return forEachAccountAddress(ns, account, addrFn) 2449 } 2450 2451 // ForEachActiveAccountAddress calls the given function with each active 2452 // address of the given account stored in the manager, breaking early on 2453 // error. 2454 // TODO(tuxcanfly): actually return only active addresses 2455 func (m *Manager) ForEachActiveAccountAddress(ns walletdb.ReadBucket, account uint32, fn func(maddr ManagedAddress) error) error { 2456 return m.ForEachAccountAddress(ns, account, fn) 2457 } 2458 2459 // ForEachActiveAddress calls the given function with each active address 2460 // stored in the manager, breaking early on error. 2461 func (m *Manager) ForEachActiveAddress(ns walletdb.ReadBucket, fn func(addr stdaddr.Address) error) error { 2462 m.mtx.Lock() 2463 defer m.mtx.Unlock() 2464 2465 addrFn := func(rowInterface interface{}) error { 2466 managedAddr, err := m.rowInterfaceToManaged(ns, rowInterface) 2467 if err != nil { 2468 return err 2469 } 2470 return fn(managedAddr.Address()) 2471 } 2472 2473 return forEachActiveAddress(ns, addrFn) 2474 } 2475 2476 // PrivateKey retreives the private key for a P2PK or P2PKH address. The 2477 // retured 'done' function should be called after the key is no longer needed to 2478 // overwrite the key with zeros. 2479 func (m *Manager) PrivateKey(ns walletdb.ReadBucket, addr stdaddr.Address) (key *secp256k1.PrivateKey, done func(), err error) { 2480 // Lock the manager mutex for writes. This protects read access to m.locked 2481 // and write access to m.returnedPrivKeys and the cached accounts. 2482 defer m.mtx.Unlock() 2483 m.mtx.Lock() 2484 2485 // NOTE: A watching only Manager may have imported private data. 2486 2487 // At this point, there are two types of addresses that must be handled: 2488 // those that are derived from a BIP0044 account and addresses for imported 2489 // keys. For BIP0044 addresses, the private key must be derived using the 2490 // account xpriv with the correct branch and child indexes. For imported 2491 // keys, the encrypted private key is simply retreived from the database and 2492 // decrypted. 2493 id, err := addressID(normalizeAddress(addr)) 2494 if err != nil { 2495 return nil, nil, err 2496 } 2497 addrInterface, err := fetchAddress(ns, id) 2498 if err != nil { 2499 return nil, nil, err 2500 } 2501 switch a := addrInterface.(type) { 2502 case *dbChainAddressRow: 2503 xpriv, err := m.deriveKeyFromPath(ns, a.account, a.branch, a.index, true) 2504 if err != nil { 2505 return nil, nil, err 2506 } 2507 serializedPriv, err := xpriv.SerializedPrivKey() 2508 if err != nil { 2509 return nil, nil, err 2510 } 2511 key = secp256k1.PrivKeyFromBytes(serializedPriv) 2512 zero(serializedPriv) 2513 2514 case *dbImportedAddressRow: 2515 privKeyBytes, err := m.cryptoKeyPriv.Decrypt(a.encryptedPrivKey) 2516 if err != nil { 2517 return nil, nil, errors.E(errors.Crypto, errors.Errorf("decrypt imported privkey: %v", err)) 2518 } 2519 key = secp256k1.PrivKeyFromBytes(privKeyBytes) 2520 // PrivKeyFromBytes creates a copy of the private key, and therefore 2521 // the decrypted private key bytes must be zeroed now. 2522 zero(privKeyBytes) 2523 2524 case *dbScriptAddressRow: 2525 return nil, nil, errors.E(errors.Invalid, "no private key for P2SH address") 2526 2527 default: 2528 return nil, nil, errors.E(errors.Invalid, errors.Errorf("address row type %T", addrInterface)) 2529 } 2530 2531 return key, key.Zero, nil 2532 } 2533 2534 // HavePrivateKey returns whether the private key for a P2PK or P2PKH address is 2535 // available when the wallet or account is unlocked. 2536 func (m *Manager) HavePrivateKey(ns walletdb.ReadBucket, addr stdaddr.Address) (bool, error) { 2537 defer m.mtx.RUnlock() 2538 m.mtx.RLock() 2539 2540 id, err := addressID(normalizeAddress(addr)) 2541 if err != nil { 2542 return false, nil 2543 } 2544 addrInterface, err := fetchAddress(ns, id) 2545 if err != nil { 2546 return false, err 2547 } 2548 switch a := addrInterface.(type) { 2549 case *dbChainAddressRow: 2550 return a.account < ImportedAddrAccount, nil 2551 case *dbImportedAddressRow: 2552 return len(a.encryptedPrivKey) != 0, nil 2553 } 2554 2555 return false, nil 2556 } 2557 2558 // RedeemScript retreives the redeem script to redeem an output paid to a P2SH 2559 // address. 2560 func (m *Manager) RedeemScript(ns walletdb.ReadBucket, addr stdaddr.Address) ([]byte, error) { 2561 id, err := addressID(normalizeAddress(addr)) 2562 if err != nil { 2563 return nil, err 2564 } 2565 return m.redeemScriptForHash160(ns, id) 2566 } 2567 2568 func (m *Manager) redeemScriptForHash160(ns walletdb.ReadBucket, hash160 []byte) ([]byte, error) { 2569 addrInterface, err := fetchAddress(ns, hash160) 2570 if err != nil { 2571 return nil, err 2572 } 2573 var script []byte 2574 switch a := addrInterface.(type) { 2575 case *dbScriptAddressRow: 2576 script = a.script 2577 case *dbChainAddressRow, *dbImportedAddressRow: 2578 err = errors.E(errors.Invalid, "redeem script lookup requires P2SH address") 2579 default: 2580 err = errors.E(errors.Invalid, errors.Errorf("address row type %T", addrInterface)) 2581 } 2582 return script, err 2583 } 2584 2585 // selectCryptoKey selects the appropriate crypto key based on the key type. An 2586 // error is returned when an invalid key type is specified or the requested key 2587 // requires the manager to be unlocked when it isn't. 2588 // 2589 // This function MUST be called with the manager lock held for reads. 2590 func (m *Manager) selectCryptoKey(keyType CryptoKeyType) (EncryptorDecryptor, error) { 2591 if keyType == CKTPrivate { 2592 // The manager must be unlocked to work with the private keys. 2593 if m.locked || m.watchingOnly { 2594 return nil, errors.E(errors.Locked) 2595 } 2596 } 2597 2598 var cryptoKey EncryptorDecryptor 2599 switch keyType { 2600 case CKTPrivate: 2601 cryptoKey = m.cryptoKeyPriv 2602 case CKTPublic: 2603 cryptoKey = m.cryptoKeyPub 2604 default: 2605 return nil, errors.E(errors.Invalid, errors.Errorf("crypto key kind %d", keyType)) 2606 } 2607 2608 return cryptoKey, nil 2609 } 2610 2611 // Encrypt in using the crypto key type specified by keyType. 2612 func (m *Manager) Encrypt(keyType CryptoKeyType, in []byte) ([]byte, error) { 2613 // Encryption must be performed under the manager mutex since the 2614 // keys are cleared when the manager is locked. 2615 m.mtx.Lock() 2616 defer m.mtx.Unlock() 2617 2618 cryptoKey, err := m.selectCryptoKey(keyType) 2619 if err != nil { 2620 return nil, err 2621 } 2622 2623 encrypted, err := cryptoKey.Encrypt(in) 2624 if err != nil { 2625 return nil, errors.E(errors.Crypto, err) 2626 } 2627 return encrypted, nil 2628 } 2629 2630 // Decrypt in using the crypto key type specified by keyType. 2631 func (m *Manager) Decrypt(keyType CryptoKeyType, in []byte) ([]byte, error) { 2632 // Decryption must be performed under the manager mutex since the 2633 // keys are cleared when the manager is locked. 2634 m.mtx.Lock() 2635 defer m.mtx.Unlock() 2636 2637 cryptoKey, err := m.selectCryptoKey(keyType) 2638 if err != nil { 2639 return nil, err 2640 } 2641 2642 decrypted, err := cryptoKey.Decrypt(in) 2643 if err != nil { 2644 return nil, errors.E(errors.Crypto, err) 2645 } 2646 return decrypted, nil 2647 } 2648 2649 // newManager returns a new locked address manager with the given parameters. 2650 func newManager(chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey, 2651 masterKeyPriv *snacl.SecretKey, cryptoKeyPub EncryptorDecryptor, 2652 cryptoKeyPrivEncrypted []byte, privPassphraseHasher hash.Hash) *Manager { 2653 2654 return &Manager{ 2655 chainParams: chainParams, 2656 locked: true, 2657 acctInfo: make(map[uint32]*accountInfo), 2658 masterKeyPub: masterKeyPub, 2659 masterKeyPriv: masterKeyPriv, 2660 cryptoKeyPub: cryptoKeyPub, 2661 cryptoKeyPrivEncrypted: cryptoKeyPrivEncrypted, 2662 cryptoKeyPriv: &cryptoKey{}, 2663 privPassphraseHasher: privPassphraseHasher, 2664 } 2665 } 2666 2667 // deriveCoinTypeKey derives the cointype key which can be used to derive the 2668 // extended key for an account according to the hierarchy described by BIP0044 2669 // given the coin type key. 2670 // 2671 // In particular this is the hierarchical deterministic extended key path: 2672 // m/44'/<coin type>' 2673 func deriveCoinTypeKey(masterNode *hdkeychain.ExtendedKey, coinType uint32) (*hdkeychain.ExtendedKey, error) { 2674 // Enforce maximum coin type. 2675 if coinType > maxCoinType { 2676 return nil, errors.E(errors.Invalid, errors.Errorf("coin type %d", coinType)) 2677 } 2678 2679 // The hierarchy described by BIP0043 is: 2680 // m/<purpose>'/* 2681 // This is further extended by BIP0044 to: 2682 // m/44'/<coin type>'/<account>'/<branch>/<address index> 2683 // 2684 // The branch is 0 for external addresses and 1 for internal addresses. 2685 2686 // Derive the purpose key as a child of the master node. 2687 purpose, err := masterNode.Child(44 + hdkeychain.HardenedKeyStart) 2688 if err != nil { 2689 return nil, err 2690 } 2691 2692 // Derive the coin type key as a child of the purpose key. 2693 coinTypeKey, err := purpose.Child(coinType + hdkeychain.HardenedKeyStart) 2694 if err != nil { 2695 return nil, err 2696 } 2697 2698 return coinTypeKey, nil 2699 } 2700 2701 // deriveAccountKey derives the extended key for an account according to the 2702 // hierarchy described by BIP0044 given the master node. 2703 // 2704 // In particular this is the hierarchical deterministic extended key path: 2705 // 2706 // m/44'/<coin type>'/<account>' 2707 func deriveAccountKey(coinTypeKey *hdkeychain.ExtendedKey, account uint32) (*hdkeychain.ExtendedKey, error) { 2708 // Enforce maximum account number. 2709 if account > MaxAccountNum { 2710 return nil, errors.E(errors.Invalid, errors.Errorf("account %d", account)) 2711 } 2712 2713 // Derive the account key as a child of the coin type key. 2714 return coinTypeKey.Child(account + hdkeychain.HardenedKeyStart) 2715 } 2716 2717 // checkBranchKeys ensures deriving the extended keys for the internal and 2718 // external branches given an account key does not result in an invalid child 2719 // error which means the chosen seed is not usable. This conforms to the 2720 // hierarchy described by BIP0044 so long as the account key is already derived 2721 // accordingly. 2722 // 2723 // In particular this is the hierarchical deterministic extended key path: 2724 // 2725 // m/44'/<coin type>'/<account>'/<branch> 2726 // 2727 // The branch is 0 for external addresses and 1 for internal addresses. 2728 func checkBranchKeys(acctKey *hdkeychain.ExtendedKey) error { 2729 // Derive the external branch as the first child of the account key. 2730 if _, err := acctKey.Child(ExternalBranch); err != nil { 2731 return err 2732 } 2733 2734 // Derive the external branch as the second child of the account key. 2735 _, err := acctKey.Child(InternalBranch) 2736 return err 2737 } 2738 2739 // loadManager returns a new address manager that results from loading it from 2740 // the passed opened database. The public passphrase is required to decrypt the 2741 // public keys. 2742 func loadManager(ns walletdb.ReadBucket, pubPassphrase []byte, chainParams *chaincfg.Params) (*Manager, error) { 2743 // Load whether or not the manager is watching-only from the db. 2744 watchingOnly, err := fetchWatchingOnly(ns) 2745 if err != nil { 2746 return nil, err 2747 } 2748 2749 // Load the master key params from the db. 2750 masterKeyPubParams, masterKeyPrivParams, err := fetchMasterKeyParams(ns) 2751 if err != nil { 2752 return nil, err 2753 } 2754 2755 // Load the crypto keys from the db. 2756 cryptoKeyPubEnc, cryptoKeyPrivEnc, err := fetchCryptoKeys(ns) 2757 if err != nil { 2758 return nil, err 2759 } 2760 2761 // When not a watching-only manager, set the master private key params, 2762 // but don't derive it now since the manager starts off locked. 2763 var masterKeyPriv snacl.SecretKey 2764 if !watchingOnly { 2765 err := masterKeyPriv.Unmarshal(masterKeyPrivParams) 2766 if err != nil { 2767 return nil, errors.E(errors.IO, errors.Errorf("unmarshal master privkey: %v", err)) 2768 } 2769 } 2770 2771 // Derive the master public key using the serialized params and provided 2772 // passphrase. 2773 var masterKeyPub snacl.SecretKey 2774 if err := masterKeyPub.Unmarshal(masterKeyPubParams); err != nil { 2775 return nil, errors.E(errors.IO, errors.Errorf("unmarshal master pubkey: %v", err)) 2776 } 2777 if err := masterKeyPub.DeriveKey(&pubPassphrase); err != nil { 2778 return nil, errors.E(errors.Passphrase) 2779 } 2780 2781 // Use the master public key to decrypt the crypto public key. 2782 cryptoKeyPub := &cryptoKey{snacl.CryptoKey{}} 2783 cryptoKeyPubCT, err := masterKeyPub.Decrypt(cryptoKeyPubEnc) 2784 if err != nil { 2785 return nil, errors.E(errors.Crypto, errors.Errorf("decrypt crypto pubkey: %v", err)) 2786 } 2787 cryptoKeyPub.CopyBytes(cryptoKeyPubCT) 2788 zero(cryptoKeyPubCT) 2789 2790 // Generate a private passphrase hasher. 2791 hasherKey := make([]byte, 32) 2792 _, err = io.ReadFull(rand.Reader, hasherKey) 2793 if err != nil { 2794 return nil, errors.E(errors.IO, err) 2795 } 2796 passHasher, err := blake2b.New256(hasherKey) 2797 if err != nil { 2798 return nil, err 2799 } 2800 2801 // Create new address manager with the given parameters. Also, override 2802 // the defaults for the additional fields which are not specified in the 2803 // call to new with the values loaded from the database. 2804 mgr := newManager(chainParams, &masterKeyPub, &masterKeyPriv, 2805 cryptoKeyPub, cryptoKeyPrivEnc, passHasher) 2806 mgr.watchingOnly = watchingOnly 2807 return mgr, nil 2808 } 2809 2810 // CoinTypes returns the legacy and SLIP0044 coin types for the chain 2811 // parameters. At the moment, the parameters have not been upgraded for the new 2812 // coin types. 2813 func CoinTypes(params *chaincfg.Params) (legacyCoinType, slip0044CoinType uint32) { 2814 return params.LegacyCoinType, params.SLIP0044CoinType 2815 } 2816 2817 // HDKeysFromSeed creates legacy and slip0044 coin keys and accout zero keys 2818 // from seed. Keys are zeroed upon any error. 2819 func HDKeysFromSeed(seed []byte, params *chaincfg.Params) (coinTypeLegacyKeyPriv, coinTypeSLIP0044KeyPriv, acctKeyLegacyPriv, acctKeySLIP0044Priv *hdkeychain.ExtendedKey, err error) { 2820 // fail will zero any successfully created keys before returning. 2821 fail := func(err error) (*hdkeychain.ExtendedKey, *hdkeychain.ExtendedKey, *hdkeychain.ExtendedKey, *hdkeychain.ExtendedKey, error) { 2822 zero := func(hdkey *hdkeychain.ExtendedKey) { 2823 if hdkey != nil { 2824 hdkey.Zero() 2825 } 2826 } 2827 zero(coinTypeLegacyKeyPriv) 2828 zero(coinTypeSLIP0044KeyPriv) 2829 zero(acctKeyLegacyPriv) 2830 zero(acctKeySLIP0044Priv) 2831 return nil, nil, nil, nil, err 2832 } 2833 2834 // Derive the master extended key from the seed. 2835 root, err := hdkeychain.NewMaster(seed, params) 2836 if err != nil { 2837 return fail(err) 2838 } 2839 2840 // Derive the cointype keys according to BIP0044. 2841 legacyCoinType, slip0044CoinType := CoinTypes(params) 2842 coinTypeLegacyKeyPriv, err = deriveCoinTypeKey(root, legacyCoinType) 2843 if err != nil { 2844 return fail(err) 2845 } 2846 coinTypeSLIP0044KeyPriv, err = deriveCoinTypeKey(root, slip0044CoinType) 2847 if err != nil { 2848 return fail(err) 2849 } 2850 2851 // Derive the account key for the first account according to BIP0044. 2852 acctKeyLegacyPriv, err = deriveAccountKey(coinTypeLegacyKeyPriv, 0) 2853 if err != nil { 2854 // The seed is unusable if the any of the children in the 2855 // required hierarchy can't be derived due to invalid child. 2856 if errors.Is(err, hdkeychain.ErrInvalidChild) { 2857 return fail(errors.E(errors.Seed, hdkeychain.ErrUnusableSeed)) 2858 } 2859 2860 return fail(err) 2861 } 2862 acctKeySLIP0044Priv, err = deriveAccountKey(coinTypeSLIP0044KeyPriv, 0) 2863 if err != nil { 2864 // The seed is unusable if the any of the children in the 2865 // required hierarchy can't be derived due to invalid child. 2866 if errors.Is(err, hdkeychain.ErrInvalidChild) { 2867 return fail(errors.E(errors.Seed, hdkeychain.ErrUnusableSeed)) 2868 } 2869 2870 return fail(err) 2871 } 2872 2873 // Ensure the branch keys can be derived for the provided seed according 2874 // to BIP0044. 2875 if err := checkBranchKeys(acctKeyLegacyPriv); err != nil { 2876 // The seed is unusable if the any of the children in the 2877 // required hierarchy can't be derived due to invalid child. 2878 if errors.Is(err, hdkeychain.ErrInvalidChild) { 2879 return fail(errors.E(errors.Seed, hdkeychain.ErrUnusableSeed)) 2880 } 2881 2882 return fail(err) 2883 } 2884 if err := checkBranchKeys(acctKeySLIP0044Priv); err != nil { 2885 // The seed is unusable if the any of the children in the 2886 // required hierarchy can't be derived due to invalid child. 2887 if errors.Is(err, hdkeychain.ErrInvalidChild) { 2888 return fail(errors.E(errors.Seed, hdkeychain.ErrUnusableSeed)) 2889 } 2890 2891 return fail(err) 2892 } 2893 return coinTypeLegacyKeyPriv, coinTypeSLIP0044KeyPriv, acctKeyLegacyPriv, acctKeySLIP0044Priv, nil 2894 } 2895 2896 // createAddressManager creates a new address manager in the given namespace. 2897 // The seed must conform to the standards described in hdkeychain.NewMaster and 2898 // will be used to create the master root node from which all hierarchical 2899 // deterministic addresses are derived. This allows all chained addresses in 2900 // the address manager to be recovered by using the same seed. 2901 // 2902 // All private and public keys and information are protected by secret keys 2903 // derived from the provided private and public passphrases. The public 2904 // passphrase is required on subsequent opens of the address manager, and the 2905 // private passphrase is required to unlock the address manager in order to gain 2906 // access to any private keys and information. 2907 func createAddressManager(ns walletdb.ReadWriteBucket, seed, pubPassphrase, privPassphrase []byte, chainParams *chaincfg.Params) error { 2908 // Return an error if the manager has already been created in the given 2909 // database namespace. 2910 if managerExists(ns) { 2911 return errors.E(errors.Exist, "address manager already exists") 2912 } 2913 2914 // Ensure the private passphrase is not empty. 2915 if len(privPassphrase) == 0 { 2916 return errors.E(errors.Invalid, "private passphrase may not be empty") 2917 } 2918 2919 // Perform the initial bucket creation and database namespace setup. 2920 if err := createManagerNS(ns); err != nil { 2921 return err 2922 } 2923 2924 // Generate the BIP0044 HD key structure to ensure the provided seed 2925 // can generate the required structure with no issues. 2926 coinTypeLegacyKeyPriv, coinTypeSLIP0044KeyPriv, acctKeyLegacyPriv, acctKeySLIP0044Priv, err := HDKeysFromSeed(seed, chainParams) 2927 if err != nil { 2928 return err 2929 } 2930 defer coinTypeLegacyKeyPriv.Zero() 2931 defer coinTypeSLIP0044KeyPriv.Zero() 2932 2933 // The address manager needs the public extended key for the account. 2934 acctKeyLegacyPub := acctKeyLegacyPriv.Neuter() 2935 acctKeySLIP0044Pub := acctKeySLIP0044Priv.Neuter() 2936 2937 // Generate new master keys. These master keys are used to protect the 2938 // crypto keys that will be generated next. 2939 scryptOpts := scryptOptionsForNet(chainParams.Net) 2940 masterKeyPub, err := newSecretKey(&pubPassphrase, scryptOpts) 2941 if err != nil { 2942 return err 2943 } 2944 masterKeyPriv, err := newSecretKey(&privPassphrase, scryptOpts) 2945 if err != nil { 2946 return err 2947 } 2948 defer masterKeyPriv.Zero() 2949 2950 // Generate new crypto public and private keys. These keys are used to 2951 // protect the actual public and private data such as addresses, and 2952 // extended keys. 2953 cryptoKeyPub, err := newCryptoKey() 2954 if err != nil { 2955 return err 2956 } 2957 cryptoKeyPriv, err := newCryptoKey() 2958 if err != nil { 2959 return err 2960 } 2961 defer cryptoKeyPriv.Zero() 2962 2963 // Encrypt the crypto keys with the associated master keys. 2964 cryptoKeyPubEnc, err := masterKeyPub.Encrypt(cryptoKeyPub.Bytes()) 2965 if err != nil { 2966 return errors.E(errors.Crypto, errors.Errorf("encrypt crypto pubkey: %v", err)) 2967 } 2968 cryptoKeyPrivEnc, err := masterKeyPriv.Encrypt(cryptoKeyPriv.Bytes()) 2969 if err != nil { 2970 return errors.E(errors.Crypto, errors.Errorf("encrypt crypto privkey: %v", err)) 2971 } 2972 2973 // Encrypt the legacy cointype keys with the associated crypto keys. 2974 coinTypeLegacyKeyPub := coinTypeLegacyKeyPriv.Neuter() 2975 ctpes := coinTypeLegacyKeyPub.String() 2976 coinTypeLegacyPubEnc, err := cryptoKeyPub.Encrypt([]byte(ctpes)) 2977 if err != nil { 2978 return errors.E(errors.Crypto, fmt.Errorf("encrypt legacy cointype pubkey: %v", err)) 2979 } 2980 ctpes = coinTypeLegacyKeyPriv.String() 2981 coinTypeLegacyPrivEnc, err := cryptoKeyPriv.Encrypt([]byte(ctpes)) 2982 if err != nil { 2983 return errors.E(errors.Crypto, fmt.Errorf("encrypt legacy cointype privkey: %v", err)) 2984 } 2985 2986 // Encrypt the SLIP0044 cointype keys with the associated crypto keys. 2987 coinTypeSLIP0044KeyPub := coinTypeSLIP0044KeyPriv.Neuter() 2988 ctpes = coinTypeSLIP0044KeyPub.String() 2989 coinTypeSLIP0044PubEnc, err := cryptoKeyPub.Encrypt([]byte(ctpes)) 2990 if err != nil { 2991 return errors.E(errors.Crypto, fmt.Errorf("encrypt SLIP0044 cointype pubkey: %v", err)) 2992 } 2993 ctpes = coinTypeSLIP0044KeyPriv.String() 2994 coinTypeSLIP0044PrivEnc, err := cryptoKeyPriv.Encrypt([]byte(ctpes)) 2995 if err != nil { 2996 return errors.E(errors.Crypto, fmt.Errorf("encrypt SLIP0044 cointype privkey: %v", err)) 2997 } 2998 2999 // Encrypt the default account keys with the associated crypto keys. 3000 apes := acctKeyLegacyPub.String() 3001 acctPubLegacyEnc, err := cryptoKeyPub.Encrypt([]byte(apes)) 3002 if err != nil { 3003 return errors.E(errors.Crypto, fmt.Errorf("encrypt account 0 pubkey: %v", err)) 3004 } 3005 apes = acctKeyLegacyPriv.String() 3006 acctPrivLegacyEnc, err := cryptoKeyPriv.Encrypt([]byte(apes)) 3007 if err != nil { 3008 return errors.E(errors.Crypto, fmt.Errorf("encrypt account 0 privkey: %v", err)) 3009 } 3010 apes = acctKeySLIP0044Pub.String() 3011 acctPubSLIP0044Enc, err := cryptoKeyPub.Encrypt([]byte(apes)) 3012 if err != nil { 3013 return errors.E(errors.Crypto, fmt.Errorf("encrypt account 0 pubkey: %v", err)) 3014 } 3015 apes = acctKeySLIP0044Priv.String() 3016 acctPrivSLIP0044Enc, err := cryptoKeyPriv.Encrypt([]byte(apes)) 3017 if err != nil { 3018 return errors.E(errors.Crypto, fmt.Errorf("encrypt account 0 privkey: %v", err)) 3019 } 3020 3021 // Save the master key params to the database. 3022 pubParams := masterKeyPub.Marshal() 3023 privParams := masterKeyPriv.Marshal() 3024 err = putMasterKeyParams(ns, pubParams, privParams) 3025 if err != nil { 3026 return err 3027 } 3028 3029 // Save the encrypted crypto keys to the database. 3030 err = putCryptoKeys(ns, cryptoKeyPubEnc, cryptoKeyPrivEnc) 3031 if err != nil { 3032 return err 3033 } 3034 3035 // Save the encrypted legacy cointype keys to the database. 3036 err = putCoinTypeLegacyKeys(ns, coinTypeLegacyPubEnc, coinTypeLegacyPrivEnc) 3037 if err != nil { 3038 return err 3039 } 3040 3041 // Save the encrypted SLIP0044 cointype keys. 3042 err = putCoinTypeSLIP0044Keys(ns, coinTypeSLIP0044PubEnc, coinTypeSLIP0044PrivEnc) 3043 if err != nil { 3044 return err 3045 } 3046 3047 // Save the fact this is not a watching-only address manager to the 3048 // database. 3049 err = putWatchingOnly(ns, false) 3050 if err != nil { 3051 return err 3052 } 3053 3054 // Set the next to use addresses as empty for the address pool. 3055 err = putNextToUseAddrPoolIdx(ns, false, DefaultAccountNum, 0) 3056 if err != nil { 3057 return err 3058 } 3059 err = putNextToUseAddrPoolIdx(ns, true, DefaultAccountNum, 0) 3060 if err != nil { 3061 return err 3062 } 3063 3064 // Save the information for the imported account to the database. Even 3065 // though the imported account is a special and restricted account, the 3066 // database used a BIP0044 row type for it. 3067 importedRow := bip0044AccountInfo(nil, nil, 0, 0, 0, 0, 0, 0, 3068 ImportedAddrAccountName, initialVersion) 3069 err = putBIP0044AccountInfo(ns, ImportedAddrAccount, importedRow) 3070 if err != nil { 3071 return err 3072 } 3073 3074 // Save the information for the default account to the database. This 3075 // account is derived from the legacy coin type. 3076 defaultRow := bip0044AccountInfo(acctPubLegacyEnc, acctPrivLegacyEnc, 3077 0, 0, 0, 0, 0, 0, defaultAccountName, initialVersion) 3078 err = putBIP0044AccountInfo(ns, DefaultAccountNum, defaultRow) 3079 if err != nil { 3080 return err 3081 } 3082 3083 // Save the account row for the 0th account derived from the coin type 3084 // 42 key. 3085 slip0044Account0Row := bip0044AccountInfo(acctPubSLIP0044Enc, acctPrivSLIP0044Enc, 3086 0, 0, 0, 0, 0, 0, defaultAccountName, initialVersion) 3087 mainBucket := ns.NestedReadWriteBucket(mainBucketName) 3088 err = mainBucket.Put(slip0044Account0RowName, serializeAccountRow(&slip0044Account0Row.dbAccountRow)) 3089 if err != nil { 3090 return errors.E(errors.IO, err) 3091 } 3092 3093 return nil 3094 } 3095 3096 // createWatchOnly creates a watching-only address manager in the given 3097 // namespace. 3098 // 3099 // All public keys and information are protected by secret keys derived from the 3100 // provided public passphrase. The public passphrase is required on subsequent 3101 // opens of the address manager. 3102 func createWatchOnly(ns walletdb.ReadWriteBucket, hdPubKey string, pubPassphrase []byte, chainParams *chaincfg.Params) (err error) { 3103 // Return an error if the manager has already been created in the given 3104 // database namespace. 3105 if managerExists(ns) { 3106 return errors.E(errors.Exist, "address manager already exists") 3107 } 3108 3109 // Perform the initial bucket creation and database namespace setup. 3110 if err := createManagerNS(ns); err != nil { 3111 return err 3112 } 3113 3114 // Load the passed public key. 3115 acctKeyPub, err := hdkeychain.NewKeyFromString(hdPubKey, chainParams) 3116 if err != nil { 3117 // The seed is unusable if the any of the children in the 3118 // required hierarchy can't be derived due to invalid child. 3119 if errors.Is(err, hdkeychain.ErrInvalidChild) { 3120 return errors.E(errors.Seed, hdkeychain.ErrUnusableSeed) 3121 } 3122 3123 return err 3124 } 3125 3126 // Ensure the branch keys can be derived for the provided seed according 3127 // to BIP0044. 3128 if err := checkBranchKeys(acctKeyPub); err != nil { 3129 // The seed is unusable if the any of the children in the 3130 // required hierarchy can't be derived due to invalid child. 3131 if errors.Is(err, hdkeychain.ErrInvalidChild) { 3132 return errors.E(errors.Seed, hdkeychain.ErrUnusableSeed) 3133 } 3134 3135 return err 3136 } 3137 3138 // Generate new master keys. These master keys are used to protect the 3139 // crypto keys that will be generated next. 3140 scryptOpts := scryptOptionsForNet(chainParams.Net) 3141 masterKeyPub, err := newSecretKey(&pubPassphrase, scryptOpts) 3142 if err != nil { 3143 return err 3144 } 3145 masterKeyPriv, err := newSecretKey(&pubPassphrase, scryptOpts) 3146 if err != nil { 3147 return err 3148 } 3149 defer masterKeyPriv.Zero() 3150 3151 // Generate new crypto public and private keys. These keys are 3152 // used to protect the actual public and private data such as addresses 3153 // and extended keys. 3154 cryptoKeyPub, err := newCryptoKey() 3155 if err != nil { 3156 return err 3157 } 3158 cryptoKeyPriv, err := newCryptoKey() 3159 if err != nil { 3160 return err 3161 } 3162 defer cryptoKeyPriv.Zero() 3163 3164 // Encrypt the crypto keys with the associated master keys. 3165 cryptoKeyPubEnc, err := masterKeyPub.Encrypt(cryptoKeyPub.Bytes()) 3166 if err != nil { 3167 return errors.E(errors.Crypto, errors.Errorf("encrypt crypto pubkey: %v", err)) 3168 } 3169 cryptoKeyPrivEnc, err := masterKeyPriv.Encrypt(cryptoKeyPriv.Bytes()) 3170 if err != nil { 3171 return errors.E(errors.Crypto, errors.Errorf("encrypt crypto privkey: %v", err)) 3172 } 3173 3174 // Encrypt the default account keys with the associated crypto keys. 3175 apes := acctKeyPub.String() 3176 acctPubEnc, err := cryptoKeyPub.Encrypt([]byte(apes)) 3177 if err != nil { 3178 return errors.E(errors.Crypto, errors.Errorf("encrypt account 0 pubkey: %v", err)) 3179 } 3180 apes = acctKeyPub.String() 3181 acctPrivEnc, err := cryptoKeyPriv.Encrypt([]byte(apes)) 3182 if err != nil { 3183 return errors.E(errors.Crypto, errors.Errorf("encrypt account 0 privkey: %v", err)) 3184 } 3185 3186 // Save the master key params to the database. 3187 pubParams := masterKeyPub.Marshal() 3188 privParams := masterKeyPriv.Marshal() 3189 err = putMasterKeyParams(ns, pubParams, privParams) 3190 if err != nil { 3191 return err 3192 } 3193 3194 // Save the encrypted crypto keys to the database. 3195 err = putCryptoKeys(ns, cryptoKeyPubEnc, cryptoKeyPrivEnc) 3196 if err != nil { 3197 return err 3198 } 3199 3200 // Save the fact this is a watching-only address manager to the database. 3201 err = putWatchingOnly(ns, true) 3202 if err != nil { 3203 return err 3204 } 3205 3206 // Set the next to use addresses as empty for the address pool. 3207 err = putNextToUseAddrPoolIdx(ns, false, DefaultAccountNum, 0) 3208 if err != nil { 3209 return err 3210 } 3211 err = putNextToUseAddrPoolIdx(ns, true, DefaultAccountNum, 0) 3212 if err != nil { 3213 return err 3214 } 3215 3216 // Save the information for the imported account to the database. 3217 importedRow := bip0044AccountInfo(nil, nil, 0, 0, 0, 0, 0, 0, 3218 ImportedAddrAccountName, initialVersion) 3219 err = putBIP0044AccountInfo(ns, ImportedAddrAccount, importedRow) 3220 if err != nil { 3221 return err 3222 } 3223 3224 // Save the information for the default account to the database. 3225 defaultRow := bip0044AccountInfo(acctPubEnc, acctPrivEnc, 0, 0, 0, 0, 0, 0, 3226 defaultAccountName, initialVersion) 3227 return putBIP0044AccountInfo(ns, DefaultAccountNum, defaultRow) 3228 }