github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/accounts/keystore/keystore.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package keystore implements encrypted storage of secp256k1 private keys.
    18  //
    19  // Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification.
    20  // See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information.
    21  package keystore
    22  
    23  import (
    24  	"crypto/ecdsa"
    25  	crand "crypto/rand"
    26  	"errors"
    27  	"fmt"
    28  	"math/big"
    29  	"os"
    30  	"path/filepath"
    31  	"reflect"
    32  	"runtime"
    33  	"sync"
    34  	"time"
    35  
    36  	"github.com/celo-org/bls-zexe/go"
    37  	"github.com/ethereum/go-ethereum/accounts"
    38  	"github.com/ethereum/go-ethereum/common"
    39  	"github.com/ethereum/go-ethereum/common/hexutil"
    40  	"github.com/ethereum/go-ethereum/core/types"
    41  	"github.com/ethereum/go-ethereum/crypto"
    42  	"github.com/ethereum/go-ethereum/crypto/bls"
    43  	"github.com/ethereum/go-ethereum/crypto/ecies"
    44  	"github.com/ethereum/go-ethereum/event"
    45  	"github.com/ethereum/go-ethereum/log"
    46  )
    47  
    48  var (
    49  	ErrLocked  = accounts.NewAuthNeededError("password or unlock")
    50  	ErrNoMatch = errors.New("no key for given address or file")
    51  	ErrDecrypt = errors.New("could not decrypt key with given passphrase")
    52  )
    53  
    54  // KeyStoreType is the reflect type of a keystore backend.
    55  var KeyStoreType = reflect.TypeOf(&KeyStore{})
    56  
    57  // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs.
    58  const KeyStoreScheme = "keystore"
    59  
    60  // Maximum time between wallet refreshes (if filesystem notifications don't work).
    61  const walletRefreshCycle = 3 * time.Second
    62  
    63  // KeyStore manages a key storage directory on disk.
    64  type KeyStore struct {
    65  	storage  keyStore                     // Storage backend, might be cleartext or encrypted
    66  	cache    *accountCache                // In-memory account cache over the filesystem storage
    67  	changes  chan struct{}                // Channel receiving change notifications from the cache
    68  	unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys)
    69  
    70  	wallets     []accounts.Wallet       // Wallet wrappers around the individual key files
    71  	updateFeed  event.Feed              // Event feed to notify wallet additions/removals
    72  	updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
    73  	updating    bool                    // Whether the event notification loop is running
    74  
    75  	mu sync.RWMutex
    76  }
    77  
    78  type unlocked struct {
    79  	*Key
    80  	abort chan struct{}
    81  }
    82  
    83  // NewKeyStore creates a keystore for the given directory.
    84  func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore {
    85  	keydir, _ = filepath.Abs(keydir)
    86  	ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP, false}}
    87  	ks.init(keydir)
    88  	return ks
    89  }
    90  
    91  // NewPlaintextKeyStore creates a keystore for the given directory.
    92  // Deprecated: Use NewKeyStore.
    93  func NewPlaintextKeyStore(keydir string) *KeyStore {
    94  	keydir, _ = filepath.Abs(keydir)
    95  	ks := &KeyStore{storage: &keyStorePlain{keydir}}
    96  	ks.init(keydir)
    97  	return ks
    98  }
    99  
   100  func (ks *KeyStore) init(keydir string) {
   101  	// Lock the mutex since the account cache might call back with events
   102  	ks.mu.Lock()
   103  	defer ks.mu.Unlock()
   104  
   105  	// Initialize the set of unlocked keys and the account cache
   106  	ks.unlocked = make(map[common.Address]*unlocked)
   107  	ks.cache, ks.changes = newAccountCache(keydir)
   108  
   109  	// TODO: In order for this finalizer to work, there must be no references
   110  	// to ks. addressCache doesn't keep a reference but unlocked keys do,
   111  	// so the finalizer will not trigger until all timed unlocks have expired.
   112  	runtime.SetFinalizer(ks, func(m *KeyStore) {
   113  		m.cache.close()
   114  	})
   115  	// Create the initial list of wallets from the cache
   116  	accs := ks.cache.accounts()
   117  	ks.wallets = make([]accounts.Wallet, len(accs))
   118  	for i := 0; i < len(accs); i++ {
   119  		ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks}
   120  	}
   121  }
   122  
   123  // Wallets implements accounts.Backend, returning all single-key wallets from the
   124  // keystore directory.
   125  func (ks *KeyStore) Wallets() []accounts.Wallet {
   126  	// Make sure the list of wallets is in sync with the account cache
   127  	ks.refreshWallets()
   128  
   129  	ks.mu.RLock()
   130  	defer ks.mu.RUnlock()
   131  
   132  	cpy := make([]accounts.Wallet, len(ks.wallets))
   133  	copy(cpy, ks.wallets)
   134  	return cpy
   135  }
   136  
   137  // refreshWallets retrieves the current account list and based on that does any
   138  // necessary wallet refreshes.
   139  func (ks *KeyStore) refreshWallets() {
   140  	// Retrieve the current list of accounts
   141  	ks.mu.Lock()
   142  	accs := ks.cache.accounts()
   143  
   144  	// Transform the current list of wallets into the new one
   145  	wallets := make([]accounts.Wallet, 0, len(accs))
   146  	events := []accounts.WalletEvent{}
   147  
   148  	for _, account := range accs {
   149  		// Drop wallets while they were in front of the next account
   150  		for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
   151  			events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
   152  			ks.wallets = ks.wallets[1:]
   153  		}
   154  		// If there are no more wallets or the account is before the next, wrap new wallet
   155  		if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
   156  			wallet := &keystoreWallet{account: account, keystore: ks}
   157  
   158  			events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
   159  			wallets = append(wallets, wallet)
   160  			continue
   161  		}
   162  		// If the account is the same as the first wallet, keep it
   163  		if ks.wallets[0].Accounts()[0] == account {
   164  			wallets = append(wallets, ks.wallets[0])
   165  			ks.wallets = ks.wallets[1:]
   166  			continue
   167  		}
   168  	}
   169  	// Drop any leftover wallets and set the new batch
   170  	for _, wallet := range ks.wallets {
   171  		events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
   172  	}
   173  	ks.wallets = wallets
   174  	ks.mu.Unlock()
   175  
   176  	// Fire all wallet events and return
   177  	for _, event := range events {
   178  		ks.updateFeed.Send(event)
   179  	}
   180  }
   181  
   182  // Subscribe implements accounts.Backend, creating an async subscription to
   183  // receive notifications on the addition or removal of keystore wallets.
   184  func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
   185  	// We need the mutex to reliably start/stop the update loop
   186  	ks.mu.Lock()
   187  	defer ks.mu.Unlock()
   188  
   189  	// Subscribe the caller and track the subscriber count
   190  	sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
   191  
   192  	// Subscribers require an active notification loop, start it
   193  	if !ks.updating {
   194  		ks.updating = true
   195  		go ks.updater()
   196  	}
   197  	return sub
   198  }
   199  
   200  // updater is responsible for maintaining an up-to-date list of wallets stored in
   201  // the keystore, and for firing wallet addition/removal events. It listens for
   202  // account change events from the underlying account cache, and also periodically
   203  // forces a manual refresh (only triggers for systems where the filesystem notifier
   204  // is not running).
   205  func (ks *KeyStore) updater() {
   206  	for {
   207  		// Wait for an account update or a refresh timeout
   208  		select {
   209  		case <-ks.changes:
   210  		case <-time.After(walletRefreshCycle):
   211  		}
   212  		// Run the wallet refresher
   213  		ks.refreshWallets()
   214  
   215  		// If all our subscribers left, stop the updater
   216  		ks.mu.Lock()
   217  		if ks.updateScope.Count() == 0 {
   218  			ks.updating = false
   219  			ks.mu.Unlock()
   220  			return
   221  		}
   222  		ks.mu.Unlock()
   223  	}
   224  }
   225  
   226  // HasAddress reports whether a key with the given address is present.
   227  func (ks *KeyStore) HasAddress(addr common.Address) bool {
   228  	return ks.cache.hasAddress(addr)
   229  }
   230  
   231  // Accounts returns all key files present in the directory.
   232  func (ks *KeyStore) Accounts() []accounts.Account {
   233  	return ks.cache.accounts()
   234  }
   235  
   236  // Decrypt decrypts an ECIES ciphertext.
   237  func (ks *KeyStore) Decrypt(a accounts.Account, c, s1, s2 []byte) ([]byte, error) {
   238  	// Look up the key to sign with and abort if it cannot be found
   239  	ks.mu.RLock()
   240  	defer ks.mu.RUnlock()
   241  
   242  	unlockedKey, found := ks.unlocked[a.Address]
   243  	if !found {
   244  		return nil, ErrLocked
   245  	}
   246  	// Import the ECDSA key as an ECIES key and decrypt the data.
   247  	eciesKey := ecies.ImportECDSA(unlockedKey.PrivateKey)
   248  	return eciesKey.Decrypt(c, s1, s2)
   249  }
   250  
   251  // Delete deletes the key matched by account if the passphrase is correct.
   252  // If the account contains no filename, the address must match a unique key.
   253  func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
   254  	// Decrypting the key isn't really necessary, but we do
   255  	// it anyway to check the password and zero out the key
   256  	// immediately afterwards.
   257  	a, key, err := ks.getDecryptedKey(a, passphrase)
   258  	if key != nil {
   259  		zeroKey(key.PrivateKey)
   260  	}
   261  	if err != nil {
   262  		return err
   263  	}
   264  	// The order is crucial here. The key is dropped from the
   265  	// cache after the file is gone so that a reload happening in
   266  	// between won't insert it into the cache again.
   267  	err = os.Remove(a.URL.Path)
   268  	if err == nil {
   269  		ks.cache.delete(a)
   270  		ks.refreshWallets()
   271  	}
   272  	return err
   273  }
   274  
   275  // SignHash calculates a ECDSA signature for the given hash. The produced
   276  // signature is in the [R || S || V] format where V is 0 or 1.
   277  func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
   278  	// Look up the key to sign with and abort if it cannot be found
   279  	ks.mu.RLock()
   280  	defer ks.mu.RUnlock()
   281  
   282  	unlockedKey, found := ks.unlocked[a.Address]
   283  	if !found {
   284  		return nil, ErrLocked
   285  	}
   286  	// Sign the hash using plain ECDSA operations
   287  	return crypto.Sign(hash, unlockedKey.PrivateKey)
   288  }
   289  
   290  func (ks *KeyStore) SignHashBLS(a accounts.Account, hash []byte) (blscrypto.SerializedSignature, error) {
   291  	// Look up the key to sign with and abort if it cannot be found
   292  	ks.mu.RLock()
   293  	defer ks.mu.RUnlock()
   294  
   295  	unlockedKey, found := ks.unlocked[a.Address]
   296  	if !found {
   297  		return blscrypto.SerializedSignature{}, ErrLocked
   298  	}
   299  
   300  	privateKeyBytes, err := blscrypto.ECDSAToBLS(unlockedKey.PrivateKey)
   301  	if err != nil {
   302  		return blscrypto.SerializedSignature{}, err
   303  	}
   304  
   305  	privateKey, err := bls.DeserializePrivateKey(privateKeyBytes)
   306  	if err != nil {
   307  		return blscrypto.SerializedSignature{}, err
   308  	}
   309  	defer privateKey.Destroy()
   310  
   311  	signature, err := privateKey.SignMessage(hash, []byte{}, false)
   312  	if err != nil {
   313  		return blscrypto.SerializedSignature{}, err
   314  	}
   315  	defer signature.Destroy()
   316  	signatureBytes, err := signature.Serialize()
   317  	if err != nil {
   318  		return blscrypto.SerializedSignature{}, err
   319  	}
   320  
   321  	return blscrypto.SerializedSignatureFromBytes(signatureBytes)
   322  }
   323  
   324  func (ks *KeyStore) SignMessageBLS(a accounts.Account, msg []byte, extraData []byte) (blscrypto.SerializedSignature, error) {
   325  	// Look up the key to sign with and abort if it cannot be found
   326  	ks.mu.RLock()
   327  	defer ks.mu.RUnlock()
   328  
   329  	unlockedKey, found := ks.unlocked[a.Address]
   330  	if !found {
   331  		return blscrypto.SerializedSignature{}, ErrLocked
   332  	}
   333  
   334  	privateKeyBytes, err := blscrypto.ECDSAToBLS(unlockedKey.PrivateKey)
   335  	if err != nil {
   336  		return blscrypto.SerializedSignature{}, err
   337  	}
   338  
   339  	privateKey, err := bls.DeserializePrivateKey(privateKeyBytes)
   340  	if err != nil {
   341  		return blscrypto.SerializedSignature{}, err
   342  	}
   343  	defer privateKey.Destroy()
   344  
   345  	signature, err := privateKey.SignMessage(msg, extraData, true)
   346  	if err != nil {
   347  		return blscrypto.SerializedSignature{}, err
   348  	}
   349  	defer signature.Destroy()
   350  	signatureBytes, err := signature.Serialize()
   351  	if err != nil {
   352  		return blscrypto.SerializedSignature{}, err
   353  	}
   354  
   355  	return blscrypto.SerializedSignatureFromBytes(signatureBytes)
   356  }
   357  
   358  func (ks *KeyStore) GenerateProofOfPossession(a accounts.Account, address common.Address) ([]byte, []byte, error) {
   359  	publicKey, err := ks.GetPublicKey(a)
   360  	if err != nil {
   361  		return nil, nil, err
   362  	}
   363  	publicKeyBytes := crypto.FromECDSAPub(publicKey)
   364  
   365  	hash := crypto.Keccak256(address.Bytes())
   366  	log.Info("msg", "msg", hexutil.Encode(hash))
   367  	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(hash), hash)
   368  	hash = crypto.Keccak256([]byte(msg))
   369  	log.Info("hash", "hash", hexutil.Encode(hash))
   370  
   371  	signature, err := ks.SignHash(a, hash)
   372  	if err != nil {
   373  		return nil, nil, err
   374  	}
   375  	return publicKeyBytes, signature, nil
   376  }
   377  
   378  func (ks *KeyStore) GenerateProofOfPossessionBLS(a accounts.Account, address common.Address) ([]byte, []byte, error) {
   379  	// Look up the key to sign with and abort if it cannot be found
   380  	ks.mu.RLock()
   381  	defer ks.mu.RUnlock()
   382  
   383  	unlockedKey, found := ks.unlocked[a.Address]
   384  	if !found {
   385  		return nil, nil, ErrLocked
   386  	}
   387  
   388  	privateKeyBytes, err := blscrypto.ECDSAToBLS(unlockedKey.PrivateKey)
   389  	if err != nil {
   390  		return nil, nil, err
   391  	}
   392  
   393  	privateKey, err := bls.DeserializePrivateKey(privateKeyBytes)
   394  	if err != nil {
   395  		return nil, nil, err
   396  	}
   397  	defer privateKey.Destroy()
   398  
   399  	signature, err := privateKey.SignPoP(address.Bytes())
   400  	if err != nil {
   401  		return nil, nil, err
   402  	}
   403  	defer signature.Destroy()
   404  	signatureBytes, err := signature.Serialize()
   405  	if err != nil {
   406  		return nil, nil, err
   407  	}
   408  
   409  	publicKey, err := privateKey.ToPublic()
   410  	if err != nil {
   411  		return nil, nil, err
   412  	}
   413  	defer publicKey.Destroy()
   414  	publicKeyBytes, err := publicKey.Serialize()
   415  	if err != nil {
   416  		return nil, nil, err
   417  	}
   418  	return publicKeyBytes, signatureBytes, nil
   419  }
   420  
   421  // Retrieve the ECDSA public key for a given account.
   422  func (ks *KeyStore) GetPublicKey(a accounts.Account) (*ecdsa.PublicKey, error) {
   423  	// Look up the key to sign with and abort if it cannot be found
   424  	ks.mu.RLock()
   425  	defer ks.mu.RUnlock()
   426  
   427  	unlockedKey, found := ks.unlocked[a.Address]
   428  	if !found {
   429  		return nil, ErrLocked
   430  	}
   431  	return &unlockedKey.PrivateKey.PublicKey, nil
   432  }
   433  
   434  // SignTx signs the given transaction with the requested account.
   435  func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   436  	// Look up the key to sign with and abort if it cannot be found
   437  	ks.mu.RLock()
   438  	defer ks.mu.RUnlock()
   439  
   440  	unlockedKey, found := ks.unlocked[a.Address]
   441  	if !found {
   442  		return nil, ErrLocked
   443  	}
   444  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   445  	if chainID != nil {
   446  		return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
   447  	}
   448  	return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
   449  }
   450  
   451  // SignHashWithPassphrase signs hash if the private key matching the given address
   452  // can be decrypted with the given passphrase. The produced signature is in the
   453  // [R || S || V] format where V is 0 or 1.
   454  func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
   455  	_, key, err := ks.getDecryptedKey(a, passphrase)
   456  	if err != nil {
   457  		return nil, err
   458  	}
   459  	defer zeroKey(key.PrivateKey)
   460  	return crypto.Sign(hash, key.PrivateKey)
   461  }
   462  
   463  // SignTxWithPassphrase signs the transaction if the private key matching the
   464  // given address can be decrypted with the given passphrase.
   465  func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   466  	_, key, err := ks.getDecryptedKey(a, passphrase)
   467  	if err != nil {
   468  		return nil, err
   469  	}
   470  	defer zeroKey(key.PrivateKey)
   471  
   472  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   473  	if chainID != nil {
   474  		return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
   475  	}
   476  	return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
   477  }
   478  
   479  // Unlock unlocks the given account indefinitely.
   480  func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
   481  	return ks.TimedUnlock(a, passphrase, 0)
   482  }
   483  
   484  // Lock removes the private key with the given address from memory.
   485  func (ks *KeyStore) Lock(addr common.Address) error {
   486  	ks.mu.Lock()
   487  	if unl, found := ks.unlocked[addr]; found {
   488  		ks.mu.Unlock()
   489  		ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
   490  	} else {
   491  		ks.mu.Unlock()
   492  	}
   493  	return nil
   494  }
   495  
   496  // TimedUnlock unlocks the given account with the passphrase. The account
   497  // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
   498  // until the program exits. The account must match a unique key file.
   499  //
   500  // If the account address is already unlocked for a duration, TimedUnlock extends or
   501  // shortens the active unlock timeout. If the address was previously unlocked
   502  // indefinitely the timeout is not altered.
   503  func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
   504  	a, key, err := ks.getDecryptedKey(a, passphrase)
   505  	if err != nil {
   506  		return err
   507  	}
   508  
   509  	ks.mu.Lock()
   510  	defer ks.mu.Unlock()
   511  	u, found := ks.unlocked[a.Address]
   512  	if found {
   513  		if u.abort == nil {
   514  			// The address was unlocked indefinitely, so unlocking
   515  			// it with a timeout would be confusing.
   516  			zeroKey(key.PrivateKey)
   517  			return nil
   518  		}
   519  		// Terminate the expire goroutine and replace it below.
   520  		close(u.abort)
   521  	}
   522  	if timeout > 0 {
   523  		u = &unlocked{Key: key, abort: make(chan struct{})}
   524  		go ks.expire(a.Address, u, timeout)
   525  	} else {
   526  		u = &unlocked{Key: key}
   527  	}
   528  	ks.unlocked[a.Address] = u
   529  	return nil
   530  }
   531  
   532  // Find resolves the given account into a unique entry in the keystore.
   533  func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
   534  	ks.cache.maybeReload()
   535  	ks.cache.mu.Lock()
   536  	a, err := ks.cache.find(a)
   537  	ks.cache.mu.Unlock()
   538  	return a, err
   539  }
   540  
   541  func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
   542  	a, err := ks.Find(a)
   543  	if err != nil {
   544  		return a, nil, err
   545  	}
   546  	key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
   547  	return a, key, err
   548  }
   549  
   550  func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
   551  	t := time.NewTimer(timeout)
   552  	defer t.Stop()
   553  	select {
   554  	case <-u.abort:
   555  		// just quit
   556  	case <-t.C:
   557  		ks.mu.Lock()
   558  		// only drop if it's still the same key instance that dropLater
   559  		// was launched with. we can check that using pointer equality
   560  		// because the map stores a new pointer every time the key is
   561  		// unlocked.
   562  		if ks.unlocked[addr] == u {
   563  			zeroKey(u.PrivateKey)
   564  			delete(ks.unlocked, addr)
   565  		}
   566  		ks.mu.Unlock()
   567  	}
   568  }
   569  
   570  // NewAccount generates a new key and stores it into the key directory,
   571  // encrypting it with the passphrase.
   572  func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
   573  	_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
   574  	if err != nil {
   575  		return accounts.Account{}, err
   576  	}
   577  	// Add the account to the cache immediately rather
   578  	// than waiting for file system notifications to pick it up.
   579  	ks.cache.add(account)
   580  	ks.refreshWallets()
   581  	return account, nil
   582  }
   583  
   584  // Export exports as a JSON key, encrypted with newPassphrase.
   585  func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
   586  	_, key, err := ks.getDecryptedKey(a, passphrase)
   587  	if err != nil {
   588  		return nil, err
   589  	}
   590  	var N, P int
   591  	if store, ok := ks.storage.(*keyStorePassphrase); ok {
   592  		N, P = store.scryptN, store.scryptP
   593  	} else {
   594  		N, P = StandardScryptN, StandardScryptP
   595  	}
   596  	return EncryptKey(key, newPassphrase, N, P)
   597  }
   598  
   599  // Import stores the given encrypted JSON key into the key directory.
   600  func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
   601  	key, err := DecryptKey(keyJSON, passphrase)
   602  	if key != nil && key.PrivateKey != nil {
   603  		defer zeroKey(key.PrivateKey)
   604  	}
   605  	if err != nil {
   606  		return accounts.Account{}, err
   607  	}
   608  	return ks.importKey(key, newPassphrase)
   609  }
   610  
   611  // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
   612  func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
   613  	key := newKeyFromECDSA(priv)
   614  	if ks.cache.hasAddress(key.Address) {
   615  		return accounts.Account{}, fmt.Errorf("account already exists")
   616  	}
   617  	return ks.importKey(key, passphrase)
   618  }
   619  
   620  func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
   621  	a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
   622  	if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
   623  		return accounts.Account{}, err
   624  	}
   625  	ks.cache.add(a)
   626  	ks.refreshWallets()
   627  	return a, nil
   628  }
   629  
   630  // Update changes the passphrase of an existing account.
   631  func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
   632  	a, key, err := ks.getDecryptedKey(a, passphrase)
   633  	if err != nil {
   634  		return err
   635  	}
   636  	return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
   637  }
   638  
   639  // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
   640  // a key file in the key directory. The key file is encrypted with the same passphrase.
   641  func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
   642  	a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
   643  	if err != nil {
   644  		return a, err
   645  	}
   646  	ks.cache.add(a)
   647  	ks.refreshWallets()
   648  	return a, nil
   649  }
   650  
   651  // zeroKey zeroes a private key in memory.
   652  func zeroKey(k *ecdsa.PrivateKey) {
   653  	b := k.D.Bits()
   654  	for i := range b {
   655  		b[i] = 0
   656  	}
   657  }