github.com/ConsenSys/Quorum@v20.10.0+incompatible/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/ethereum/go-ethereum/accounts"
    37  	"github.com/ethereum/go-ethereum/common"
    38  	"github.com/ethereum/go-ethereum/core/types"
    39  	"github.com/ethereum/go-ethereum/crypto"
    40  	"github.com/ethereum/go-ethereum/event"
    41  	"github.com/ethereum/go-ethereum/log"
    42  )
    43  
    44  var (
    45  	ErrLocked  = accounts.NewAuthNeededError("password or unlock")
    46  	ErrNoMatch = errors.New("no key for given address or file")
    47  	ErrDecrypt = errors.New("could not decrypt key with given password")
    48  )
    49  
    50  // KeyStoreType is the reflect type of a keystore backend.
    51  var KeyStoreType = reflect.TypeOf(&KeyStore{})
    52  
    53  // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs.
    54  const KeyStoreScheme = "keystore"
    55  
    56  // Maximum time between wallet refreshes (if filesystem notifications don't work).
    57  const walletRefreshCycle = 3 * time.Second
    58  
    59  // KeyStore manages a key storage directory on disk.
    60  type KeyStore struct {
    61  	storage  keyStore                     // Storage backend, might be cleartext or encrypted
    62  	cache    *accountCache                // In-memory account cache over the filesystem storage
    63  	changes  chan struct{}                // Channel receiving change notifications from the cache
    64  	unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys)
    65  
    66  	wallets     []accounts.Wallet       // Wallet wrappers around the individual key files
    67  	updateFeed  event.Feed              // Event feed to notify wallet additions/removals
    68  	updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
    69  	updating    bool                    // Whether the event notification loop is running
    70  
    71  	mu sync.RWMutex
    72  }
    73  
    74  type unlocked struct {
    75  	*Key
    76  	abort chan struct{}
    77  }
    78  
    79  // NewKeyStore creates a keystore for the given directory.
    80  func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore {
    81  	keydir, _ = filepath.Abs(keydir)
    82  	ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP, false}}
    83  	ks.init(keydir)
    84  	return ks
    85  }
    86  
    87  // NewPlaintextKeyStore creates a keystore for the given directory.
    88  // Deprecated: Use NewKeyStore.
    89  func NewPlaintextKeyStore(keydir string) *KeyStore {
    90  	keydir, _ = filepath.Abs(keydir)
    91  	ks := &KeyStore{storage: &keyStorePlain{keydir}}
    92  	ks.init(keydir)
    93  	return ks
    94  }
    95  
    96  func (ks *KeyStore) init(keydir string) {
    97  	// Lock the mutex since the account cache might call back with events
    98  	ks.mu.Lock()
    99  	defer ks.mu.Unlock()
   100  
   101  	// Initialize the set of unlocked keys and the account cache
   102  	ks.unlocked = make(map[common.Address]*unlocked)
   103  	ks.cache, ks.changes = newAccountCache(keydir)
   104  
   105  	// TODO: In order for this finalizer to work, there must be no references
   106  	// to ks. addressCache doesn't keep a reference but unlocked keys do,
   107  	// so the finalizer will not trigger until all timed unlocks have expired.
   108  	runtime.SetFinalizer(ks, func(m *KeyStore) {
   109  		m.cache.close()
   110  	})
   111  	// Create the initial list of wallets from the cache
   112  	accs := ks.cache.accounts()
   113  	ks.wallets = make([]accounts.Wallet, len(accs))
   114  	for i := 0; i < len(accs); i++ {
   115  		ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks}
   116  	}
   117  }
   118  
   119  // Wallets implements accounts.Backend, returning all single-key wallets from the
   120  // keystore directory.
   121  func (ks *KeyStore) Wallets() []accounts.Wallet {
   122  	// Make sure the list of wallets is in sync with the account cache
   123  	ks.refreshWallets()
   124  
   125  	ks.mu.RLock()
   126  	defer ks.mu.RUnlock()
   127  
   128  	cpy := make([]accounts.Wallet, len(ks.wallets))
   129  	copy(cpy, ks.wallets)
   130  	return cpy
   131  }
   132  
   133  // refreshWallets retrieves the current account list and based on that does any
   134  // necessary wallet refreshes.
   135  func (ks *KeyStore) refreshWallets() {
   136  	// Retrieve the current list of accounts
   137  	ks.mu.Lock()
   138  	accs := ks.cache.accounts()
   139  
   140  	// Transform the current list of wallets into the new one
   141  	var (
   142  		wallets = make([]accounts.Wallet, 0, len(accs))
   143  		events  []accounts.WalletEvent
   144  	)
   145  
   146  	for _, account := range accs {
   147  		// Drop wallets while they were in front of the next account
   148  		for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
   149  			events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
   150  			ks.wallets = ks.wallets[1:]
   151  		}
   152  		// If there are no more wallets or the account is before the next, wrap new wallet
   153  		if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
   154  			wallet := &keystoreWallet{account: account, keystore: ks}
   155  
   156  			events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
   157  			wallets = append(wallets, wallet)
   158  			continue
   159  		}
   160  		// If the account is the same as the first wallet, keep it
   161  		if ks.wallets[0].Accounts()[0] == account {
   162  			wallets = append(wallets, ks.wallets[0])
   163  			ks.wallets = ks.wallets[1:]
   164  			continue
   165  		}
   166  	}
   167  	// Drop any leftover wallets and set the new batch
   168  	for _, wallet := range ks.wallets {
   169  		events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
   170  	}
   171  	ks.wallets = wallets
   172  	ks.mu.Unlock()
   173  
   174  	// Fire all wallet events and return
   175  	for _, event := range events {
   176  		ks.updateFeed.Send(event)
   177  	}
   178  }
   179  
   180  // Subscribe implements accounts.Backend, creating an async subscription to
   181  // receive notifications on the addition or removal of keystore wallets.
   182  func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
   183  	// We need the mutex to reliably start/stop the update loop
   184  	ks.mu.Lock()
   185  	defer ks.mu.Unlock()
   186  
   187  	// Subscribe the caller and track the subscriber count
   188  	sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
   189  
   190  	// Subscribers require an active notification loop, start it
   191  	if !ks.updating {
   192  		ks.updating = true
   193  		go ks.updater()
   194  	}
   195  	return sub
   196  }
   197  
   198  // updater is responsible for maintaining an up-to-date list of wallets stored in
   199  // the keystore, and for firing wallet addition/removal events. It listens for
   200  // account change events from the underlying account cache, and also periodically
   201  // forces a manual refresh (only triggers for systems where the filesystem notifier
   202  // is not running).
   203  func (ks *KeyStore) updater() {
   204  	for {
   205  		// Wait for an account update or a refresh timeout
   206  		select {
   207  		case <-ks.changes:
   208  		case <-time.After(walletRefreshCycle):
   209  		}
   210  		// Run the wallet refresher
   211  		ks.refreshWallets()
   212  
   213  		// If all our subscribers left, stop the updater
   214  		ks.mu.Lock()
   215  		if ks.updateScope.Count() == 0 {
   216  			ks.updating = false
   217  			ks.mu.Unlock()
   218  			return
   219  		}
   220  		ks.mu.Unlock()
   221  	}
   222  }
   223  
   224  // HasAddress reports whether a key with the given address is present.
   225  func (ks *KeyStore) HasAddress(addr common.Address) bool {
   226  	return ks.cache.hasAddress(addr)
   227  }
   228  
   229  // Accounts returns all key files present in the directory.
   230  func (ks *KeyStore) Accounts() []accounts.Account {
   231  	return ks.cache.accounts()
   232  }
   233  
   234  // Delete deletes the key matched by account if the passphrase is correct.
   235  // If the account contains no filename, the address must match a unique key.
   236  func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
   237  	// Decrypting the key isn't really necessary, but we do
   238  	// it anyway to check the password and zero out the key
   239  	// immediately afterwards.
   240  	a, key, err := ks.getDecryptedKey(a, passphrase)
   241  	if key != nil {
   242  		zeroKey(key.PrivateKey)
   243  	}
   244  	if err != nil {
   245  		return err
   246  	}
   247  	// The order is crucial here. The key is dropped from the
   248  	// cache after the file is gone so that a reload happening in
   249  	// between won't insert it into the cache again.
   250  	err = os.Remove(a.URL.Path)
   251  	if err == nil {
   252  		ks.cache.delete(a)
   253  		ks.refreshWallets()
   254  	}
   255  	return err
   256  }
   257  
   258  // SignHash calculates a ECDSA signature for the given hash. The produced
   259  // signature is in the [R || S || V] format where V is 0 or 1.
   260  func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
   261  	// Look up the key to sign with and abort if it cannot be found
   262  	ks.mu.RLock()
   263  	defer ks.mu.RUnlock()
   264  
   265  	unlockedKey, found := ks.unlocked[a.Address]
   266  	if !found {
   267  		return nil, ErrLocked
   268  	}
   269  	// Sign the hash using plain ECDSA operations
   270  	return crypto.Sign(hash, unlockedKey.PrivateKey)
   271  }
   272  
   273  // SignTx signs the given transaction with the requested account.
   274  func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   275  	// Look up the key to sign with and abort if it cannot be found
   276  	ks.mu.RLock()
   277  	defer ks.mu.RUnlock()
   278  
   279  	unlockedKey, found := ks.unlocked[a.Address]
   280  	if !found {
   281  		return nil, ErrLocked
   282  	}
   283  
   284  	// start quorum specific
   285  	if tx.IsPrivate() {
   286  		log.Info("Private transaction signing with QuorumPrivateTxSigner")
   287  		return types.SignTx(tx, types.QuorumPrivateTxSigner{}, unlockedKey.PrivateKey)
   288  	} // End quorum specific
   289  
   290  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   291  	if chainID != nil {
   292  		return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
   293  	}
   294  	return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
   295  }
   296  
   297  // SignHashWithPassphrase signs hash if the private key matching the given address
   298  // can be decrypted with the given passphrase. The produced signature is in the
   299  // [R || S || V] format where V is 0 or 1.
   300  func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
   301  	_, key, err := ks.getDecryptedKey(a, passphrase)
   302  	if err != nil {
   303  		return nil, err
   304  	}
   305  	defer zeroKey(key.PrivateKey)
   306  	return crypto.Sign(hash, key.PrivateKey)
   307  }
   308  
   309  // SignTxWithPassphrase signs the transaction if the private key matching the
   310  // given address can be decrypted with the given passphrase.
   311  func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
   312  	_, key, err := ks.getDecryptedKey(a, passphrase)
   313  	if err != nil {
   314  		return nil, err
   315  	}
   316  	defer zeroKey(key.PrivateKey)
   317  
   318  	if tx.IsPrivate() {
   319  		return types.SignTx(tx, types.QuorumPrivateTxSigner{}, key.PrivateKey)
   320  	}
   321  	// Depending on the presence of the chain ID, sign with EIP155 or homestead
   322  	if chainID != nil {
   323  		return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
   324  	}
   325  	return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
   326  }
   327  
   328  // Unlock unlocks the given account indefinitely.
   329  func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
   330  	return ks.TimedUnlock(a, passphrase, 0)
   331  }
   332  
   333  // Lock removes the private key with the given address from memory.
   334  func (ks *KeyStore) Lock(addr common.Address) error {
   335  	ks.mu.Lock()
   336  	if unl, found := ks.unlocked[addr]; found {
   337  		ks.mu.Unlock()
   338  		ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
   339  	} else {
   340  		ks.mu.Unlock()
   341  	}
   342  	return nil
   343  }
   344  
   345  // TimedUnlock unlocks the given account with the passphrase. The account
   346  // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
   347  // until the program exits. The account must match a unique key file.
   348  //
   349  // If the account address is already unlocked for a duration, TimedUnlock extends or
   350  // shortens the active unlock timeout. If the address was previously unlocked
   351  // indefinitely the timeout is not altered.
   352  func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
   353  	a, key, err := ks.getDecryptedKey(a, passphrase)
   354  	if err != nil {
   355  		return err
   356  	}
   357  
   358  	ks.mu.Lock()
   359  	defer ks.mu.Unlock()
   360  	u, found := ks.unlocked[a.Address]
   361  	if found {
   362  		if u.abort == nil {
   363  			// The address was unlocked indefinitely, so unlocking
   364  			// it with a timeout would be confusing.
   365  			zeroKey(key.PrivateKey)
   366  			return nil
   367  		}
   368  		// Terminate the expire goroutine and replace it below.
   369  		close(u.abort)
   370  	}
   371  	if timeout > 0 {
   372  		u = &unlocked{Key: key, abort: make(chan struct{})}
   373  		go ks.expire(a.Address, u, timeout)
   374  	} else {
   375  		u = &unlocked{Key: key}
   376  	}
   377  	ks.unlocked[a.Address] = u
   378  	return nil
   379  }
   380  
   381  // Find resolves the given account into a unique entry in the keystore.
   382  func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
   383  	ks.cache.maybeReload()
   384  	ks.cache.mu.Lock()
   385  	a, err := ks.cache.find(a)
   386  	ks.cache.mu.Unlock()
   387  	return a, err
   388  }
   389  
   390  func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
   391  	a, err := ks.Find(a)
   392  	if err != nil {
   393  		return a, nil, err
   394  	}
   395  	key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
   396  	return a, key, err
   397  }
   398  
   399  func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
   400  	t := time.NewTimer(timeout)
   401  	defer t.Stop()
   402  	select {
   403  	case <-u.abort:
   404  		// just quit
   405  	case <-t.C:
   406  		ks.mu.Lock()
   407  		// only drop if it's still the same key instance that dropLater
   408  		// was launched with. we can check that using pointer equality
   409  		// because the map stores a new pointer every time the key is
   410  		// unlocked.
   411  		if ks.unlocked[addr] == u {
   412  			zeroKey(u.PrivateKey)
   413  			delete(ks.unlocked, addr)
   414  		}
   415  		ks.mu.Unlock()
   416  	}
   417  }
   418  
   419  // NewAccount generates a new key and stores it into the key directory,
   420  // encrypting it with the passphrase.
   421  func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
   422  	_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
   423  	if err != nil {
   424  		return accounts.Account{}, err
   425  	}
   426  	// Add the account to the cache immediately rather
   427  	// than waiting for file system notifications to pick it up.
   428  	ks.cache.add(account)
   429  	ks.refreshWallets()
   430  	return account, nil
   431  }
   432  
   433  // Export exports as a JSON key, encrypted with newPassphrase.
   434  func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
   435  	_, key, err := ks.getDecryptedKey(a, passphrase)
   436  	if err != nil {
   437  		return nil, err
   438  	}
   439  	var N, P int
   440  	if store, ok := ks.storage.(*keyStorePassphrase); ok {
   441  		N, P = store.scryptN, store.scryptP
   442  	} else {
   443  		N, P = StandardScryptN, StandardScryptP
   444  	}
   445  	return EncryptKey(key, newPassphrase, N, P)
   446  }
   447  
   448  // Import stores the given encrypted JSON key into the key directory.
   449  func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
   450  	key, err := DecryptKey(keyJSON, passphrase)
   451  	if key != nil && key.PrivateKey != nil {
   452  		defer zeroKey(key.PrivateKey)
   453  	}
   454  	if err != nil {
   455  		return accounts.Account{}, err
   456  	}
   457  	return ks.importKey(key, newPassphrase)
   458  }
   459  
   460  // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
   461  func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
   462  	key := newKeyFromECDSA(priv)
   463  	if ks.cache.hasAddress(key.Address) {
   464  		return accounts.Account{}, fmt.Errorf("account already exists")
   465  	}
   466  	return ks.importKey(key, passphrase)
   467  }
   468  
   469  func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
   470  	a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
   471  	if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
   472  		return accounts.Account{}, err
   473  	}
   474  	ks.cache.add(a)
   475  	ks.refreshWallets()
   476  	return a, nil
   477  }
   478  
   479  // Update changes the passphrase of an existing account.
   480  func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
   481  	a, key, err := ks.getDecryptedKey(a, passphrase)
   482  	if err != nil {
   483  		return err
   484  	}
   485  	return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
   486  }
   487  
   488  // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
   489  // a key file in the key directory. The key file is encrypted with the same passphrase.
   490  func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
   491  	a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
   492  	if err != nil {
   493  		return a, err
   494  	}
   495  	ks.cache.add(a)
   496  	ks.refreshWallets()
   497  	return a, nil
   498  }
   499  
   500  // zeroKey zeroes a private key in memory.
   501  func zeroKey(k *ecdsa.PrivateKey) {
   502  	b := k.D.Bits()
   503  	for i := range b {
   504  		b[i] = 0
   505  	}
   506  }