github.com/ava-labs/subnet-evm@v0.6.4/accounts/keystore/keystore.go (about)

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